Skip to content
Advertisement

Export CSV for Excel

I’m writing a CSV file in PHP using fputcsv($file, $data).
It all works, however I can’t just open it in Excel but have to import it and specify the encoding and which delimiter to use (in a wizard).
I’ve seen exports from other websites that open correctly just by clicking on them and now would like to know what I should do to my file to achieve that.

I tried using this library: http://code.google.com/p/parsecsv-for-php/
But I couldn’t even get it to run and am not really confident if it would really help me…

Advertisement

Answer

Despite the “C=comma” in CVS, Excel uses your locale native separator. So supposing fputcsv always uses a comma, it won’t work, if your locale separator is for example a semicolon.

What Google AdSense does, when you click “Export to Excel CSV”, is that it uses Tab as a separator. And that works.

To replicate that, set the third parameter (delimiter) of fputcsv to override the default comma. E.g. for Tab use: fputcsv($handle, $fields, "t");

Compare the format of the CSV that works for you against the one generated by fputcsv.

Consider including example of both in your question. You might get better answers.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement