Ever needed export data to a CSV file (Comma Separated Value)? If you don’t know what a CSV is it is a bunch of values that are separated by a , . An example is:
first value, second value, third value fourth value, fifth value, sixth value
Every value before a comma is new cell in the spreadsheet and everything after each new line is the start of a new row. The above would produce something like:
| first value | second value | third value |
| fourth value | fifth value | sixth value |
To accomplish this in PHP you can go about things two ways: arrays or strings.
The array approach:
$row[] = 'first value'; $row[] = 'second value'; $row[] = 'third value'; $data .= join(',', $row)."\n"; // Join all values without any trailing commas and add a new line $row = ''; // We must clear the previous values $row[] = 'fourth value'; $row[] = 'fifth value'; $row[] = 'sixth value'; $data .= join(',', $row)."\n"; // Output the headers to download the file header("Content-type: application/x-msdownload"); header("Content-Disposition: attachment; filename=log.csv"); header("Pragma: no-cache"); header("Expires: 0"); echo $data;
Using strings:
$row = 'first value,'; $row .= 'second value,'; $row .= 'third value'; $data .= $row."\n"; $row = 'fourth value,'; $row .= 'fifth value,'; $row .= 'sixth value'; $data .= $row."\n"; // Output the headers to download the file header("Content-type: application/x-msdownload"); header("Content-Disposition: attachment; filename=log.csv"); header("Pragma: no-cache"); header("Expires: 0"); echo $data;
The problem with using strings to create the CSV file is you have to pay attention to the last value in each row and strip out the last comma or not insert the last comma. You will also notice in the string version the $row .= ‘value’;
The period before the = adds that value to the previous $row value.
On the next page I will show you how to handle line breaks, quotes and commas in your data.
Pages: 1 2



(5 votes, average: 4.8 out of 5)
January 29th, 2007 at 5:18 am
hi guys,
This article is very helpful to us.
Mahadev
February 6th, 2007 at 10:15 pm
Awesomeness! Thanks
November 19th, 2007 at 10:33 am
This does not work with IE7…get an errors saying that there is a problem trying to download the php file….works great in firefox tho…
May 7th, 2008 at 10:15 am
[…] WLScripting.com ยป Export data to CSV Comma Separated Value […]
June 6th, 2008 at 7:23 am
Hello all,
A bit of modification in the above code and appending it to my existing code, helped me a lot….
Thanks…..God Bless