Export data to CSV (Comma Separated Value)
By: Daniel
One thing you are first going to wonder is how you can put commas in your CSV and have that comma stay in one cell instead of multiple cells. The solution to this is double quotes.
Example:
"first, value", second value, third value fourth value, "fifth, value", "sixth, value"
The quotes escape the commas. The quotes also work on new lines (\n).
Example:
"first value", second value, third value fourth value, "fifth, value", sixth value
Now you are wondering, what do I do about quotes?
Example:
first value, """second"" value", third value fourth value, fifth value, sixth value
You have to put two quotes instead of one.
Some PHP code that I use on projects to do this is:
function parseCSVComments($comments) { $comments = str_replace('"', '""', $comments); // First off escape all " and make them "" if(eregi(",", $comments) or eregi("\n", $comments)) { // Check if I have any commas or new lines return '"'.$comments.'"'; // If I have new lines or commas escape them } else { return $comments; // If no new lines or commas just return the value } } $csvSafeComment = parseCSVComments('your value here');
Hope everybody gets good use of this!
There is now a more advanced tutorial here: Advanced CSV Export that deals more with databases.
Pages: 1 2




















(8 votes, average: 4.88 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
September 23rd, 2008 at 6:54 am
hello guys,
Can anybody help me that if “first value” contain comma separated value like “first,value” and I want to export to csv in first cell then how can I do ?
another problem is that how can I give the font style to the cell ?
please help me guys
September 23rd, 2008 at 9:19 pm
Ahmad, check out page 2 of this tutorial and that should fix the issue you are having. http://www.wlscripting.com/tutorial/36/2/
August 23rd, 2009 at 2:26 am
What about commas and special characters?