user1564018 user1564018 - 6 months ago 49
PHP Question

fputcsv adds a line ending on the last element

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);

Answer

I found this solution on another question: http://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.

Comments