Converting arrays to CSV

I’ve been dealing with some large (Gb+) CSV files, taking existing csv files, parsing them, combining fields from each and then serving them. Problem is, I wasn’t writing the resulting CSV to another file, I needed to serve it straight away.

Rather than implode array fields or iterate through each field in each row building strings, I was able to make use of the little used php://output wrapper and pretend I was writing to a file:
[php]
$data = array('field1',
'field2, now with commas',
'field three, with commas and "quotes"'
);
$fp = fopen('php://output', 'a');
header("Content-type: application/csv");
fputcsv($fp, $data);
fclose($fp);
?>[/php]

I didn’t have to write anything to implode fields or escape quotes and the end user can start downloading the file straight away. Nifty.

Share this:
  • Digg
  • del.icio.us
  • Facebook
  • Google
  • StumbleUpon
  • Reddit
  • Ma.gnolia
  • TwitThis

Trackback URL

Comments are closed.