fputcsv adds a line ending on the last element

匿名 (未验证) 提交于 2019-12-03 01:12:01

问题:

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('test.csv', 'w');  foreach($array as $v)     fputcsv($handle, $v);  fclose($handle);

The resulting file always has a blank line at the end of the file, because fputcsv doesn't know that this is the last line. Any (simple) ideas on how to prevent this?

EDIT:

The original question is now irrelevant (to me, but maybe someone will need to do this). fputcsv is supposed to add a new line, even at the end of the document, and this is the expected behavior of all csv files.

I marked the answer that solves the original question, even though it isn't relevant to me anymore.

So in my context, I needed to check if the last line (or any line) of the array is NULL (otherwise PHP will through up a Warning that fputcsv's 2nd parameter is null). Here is my updated script if anyone is interested:

$array = [     [1,2,3],     [4,5,6] ];  $handle = fopen('test.csv', 'w');  foreach($array as $v)     if($v != NULL)         fputcsv($handle, $v);  fclose($handle);

回答1:

I found this solution on another question: https://stackoverflow.com/a/8354413/1564018

$stat = fstat($handle); ftruncate($handle, $stat['size']-1);

I added these two lines after fputcsv() and they removed the last new line character, removing the blank line at the end of the file.



回答2:

Like @Barmar says, all lines have a line ending, let's say \n. What you see as a blank line at the end of the file is your editor doing that. A truly blank line is two line-ending characters in succession. (\n\n for example)

Imagine you have a blank file:

(EOF)

If you fputcsv this: array(0,"hello",3323) you get

(0,hello,3323\nEOF)

given PHP docs:

fputcsv() formats a line (passed as a fields array) as CSV and write it (terminated by a newline) to the specified file handle.

A blank line in your editor is expected then. But in the file there's no such thing.



回答3:

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) { }


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!