fputcsv adds a line ending on the last element

前端 未结 4 1756
攒了一身酷
攒了一身酷 2020-12-22 05:31

I have a basic PHP script that creates a csv file from an array. Here is an example of the code:

$array = [
    [1,2,3],
    [4,5,6]
];

$handle = fopen(\'te         


        
4条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-22 06:10

    fputcsv adds a new line after each line, that's how it works. From the docs:

    fputcsv() formats a line (passed as a fields array) as CSV and write it (terminated by a newline)

    A new line at the end of a file is not an error, or something you need to worry about. Don't try to remove it, just leave it.

    In the comments, you mention you got an error:

    Warning: fputcsv() expects parameter 2 to be array, boolean given

    This is probably because you are not using fgetcsv correctly. It returns FALSE when it hits the end of the file (the new line). The docs show you how to use it correctly:

    while (($data = fgetcsv($handle)) !== FALSE) {
    }
    

提交回复
热议问题