How can I change the line endings used by fputcsv?

I create a CSV file to be downloaded by our client using

$output = fopen('php://output', 'w'); 

and using fputcsv() to write data to a CSV file that is downloaded by the client.

I am running PHP on Linux, and therefore line endings are not interpreted by many Windows applications.

I could write the CSV file to a directory on the server, read it and execute str_replace() from \n to \r\n , but this seems like a pretty awkward way to solve the problem. Is there a way to perform the conversion without creating a physical file?

+7
source share
4 answers

You can use stream filters for this. This example is written to a physical file, but it should work fine for php://output .

 // filter class that applies CRLF line endings class crlf_filter extends php_user_filter { function filter($in, $out, &$consumed, $closing) { while ($bucket = stream_bucket_make_writeable($in)) { // make sure the line endings aren't already CRLF $bucket->data = preg_replace("/(?<!\r)\n/", "\r\n", $bucket->data); $consumed += $bucket->datalen; stream_bucket_append($out, $bucket); } return PSFS_PASS_ON; } } // register the filter stream_filter_register('crlf', 'crlf_filter'); $f = fopen('test.csv', 'wt'); // attach filter to output file stream_filter_append($f, 'crlf'); // start writing fputcsv($f, array('1 1', '2 2')); fclose($f); 
+17
source

Not sure if you can do this using PHP itself. There may be a way to change PHP EOL to write files, but it probably depends on the system. You do not have a Windows system that you could ping, right?;)

As for the real solution, instead of str_replace , you can use the Linux unix2dos program (inverse to dos2unix ) in dos2unix , provided that it is installed:

 fputcsv($fh ...) exec("unix2dos " . escapeshellarg($filename)); 
+2
source
  • Create a file with line ending \ n on a Linux machine.
  • ASCII FTP file from a Linux computer to a Windows computer.
  • Hey presto! All line endings are now in a file on a Windows computer
+1
source

Instead of writing a file, the best solution is to use output buffering

 function output($buffer) { return str_replace("\r", "\r\n", $buffer); } ob_start('output'); fputcsv(....); 
-one
source

All Articles