PHP export to CSV

Here's a short PHP script to export data to a CSV file.

I'll start with a PHP array. You can extend this to query a database or something similar.


//the stuff we want to export
$arr = array();
$arr[] = array('Banana', 'Yellow');
$arr[] = array('Apple', 'Red');
$arr[] = array('Apple', 'Green');
$arr[] = array('Orange', 'Orange');
$arr[] = array('Grape', 'Green');
$arr[] = array('Mandarin', 'Orange');
$arr[] = array('Kiwifruit', 'Green');

Now we build our CSV output as we loop through the array with the foreach construct.


$csv = "Fruit,Colour\n";
foreach($arr as $row){
$csv .= "{$row[0]},{$row[1]}\n";
}

Then we output the file to the web browser with the headers set to our content type.


header ( "Content-Type: application/force-download" );
header ( "Content-Type: application/octet-stream" );
header ( "Content-Type: application/download" );
header ( "Content-Type: text/csv" );
header ( "Content-Disposition: attachment; filename=fruit.csv");




Probably easier to do: $csv

Probably easier to do:

$csv = "Fruit,Colour\n";
foreach($arr as $row) {
$csv .= implode( ', ', $row ) ."\n";
}

Then you don't have to change the code when the number of columns changes.

Also, with HTTP headers, you can only have one header of "Content-Type" and "application/octet-stream" means to download, so the others are redundant.

Cheers,
Matt

Oh!

Thanks for your corrections!

The explode part should have been obvious... DOH!

Post new comment

  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd>
  • Lines and paragraphs break automatically.

More information about formatting options