Archive for February, 2011

Creating csv content

Friday, February 25th, 2011

It is tempting to simply generate CSV data with writing comma-separated  array-values.

implode(",", $data_array);

Unfortunately this obvious way of doing turns out to be a bad idea. Often it seems to be working at first, but eventually you’ll be faced with annoying bugs, wrongly escaped data.

Fortunately, PHP has a native function to write CSV values to a file.

fputcsv()

With a little trick you can use this function to write values to the screen.
Use the built-in streamwrappers:

 $outstream = fopen("php://output", 'w');
 fputcsv($outstream, $data_array, ',', '"');
 fclose($outstream);

This will echo the data to the screen.
Most people won’t know `php://output`. A pity it’s really powerful.

Your are browsing
the Archives of My Beloved PHP for February 2011.
Categories
Archives
Links