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:

<?php
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

1 Star2 Stars3 Stars4 Stars5 Stars (8 votes, average: 4.88 out of 5)
Loading ... Loading ...

8 Responses to “Export data to CSV (Comma Separated Value)”

  1. mahadev Says:

    hi guys,

    This article is very helpful to us.

    Mahadev

  2. Isaac Says:

    Awesomeness! Thanks

  3. Thad Says:

    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…

  4. Export php generated data to CSV « A Guilty Pleasure Says:

    [...] WLScripting.com » Export data to CSV Comma Separated Value [...]

  5. Sanyogita Says:

    Hello all,
    A bit of modification in the above code and appending it to my existing code, helped me a lot….
    Thanks…..God Bless

  6. Ahmad Says:

    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

  7. Daniel Says:

    Ahmad, check out page 2 of this tutorial and that should fix the issue you are having. http://www.wlscripting.com/tutorial/36/2/

  8. Arvind Says:

    What about commas and special characters?

Leave a Reply

geovisitors