0
votes

I'm trying to export an array to a CSV file using PHP's fputcsv function. However I get two completely different behaviours when opening the file in Excel 2007 and 2010.

In Excel 2007 I get what I want since all the fields are in its own separate column like this:

aaa | bbb | ccc | dddd

123 | 456 | 789

"aaa" | "bbb" |

But in Excel 2010 all the fields are on the same column like this:

aaa,bbb,ccc,dddd
123,456,789
"aaa","""bbb"""

How can I get the Excel 2007 behaviour for both Excel 2007 and 2010?

I used the following script:

        $filename = "test.csv";
    //header("Content-Type: application/vnd.ms-excel;");
    header('Content-Type: text/csv');
    header('Content-Disposition: attachment; filename="' . $filename . '"');
    header("Pragma: no-cache");
    header("Expires: 0");
    $list = array (
        array('aaa', 'bbb', 'ccc', 'dddd'),
        array('123', '456', '789'),
        array('"aaa"', '"bbb"')
    );
    $fp = fopen("php://output", 'w');
    foreach ($list as $fields) {
        fputcsv($fp, $fields);
    }
    fclose($fp);

I've tried using header("Content-Type: application/vnd.ms-excel;"); or header('Content-Type: text/csv'); but I get the same behaviour. :S

Thank you in advance.

EDIT: I just ended up using PHPExcel. It's a great library!!

2
remember to state delimiter fputcsv($fp, $fields, ",");zkanoca
I just changed the line to fputcsv($fp, $fields, ","); but the behaviour is the same.. Any ideas on what's wrong?SnitramSD
Maybe Microsoft's itself! Who knows?zkanoca

2 Answers

1
votes

There is a setting to change the delimiter in excel, set it to the ',' character and it will work.

Read this: http://office.microsoft.com/en-gb/excel-help/import-or-export-text-txt-or-csv-files-HP010099725.aspx#BMimport_data_from_a_text_file_by_openi

1
votes

This isn't PHP's fault; it's Excel's fault for being rubbish at importing CSV.

There are a number of bugs in Excel's CSV handling (or more accurately, the default CSV handling when you double-click a CSV file's icon to open it in Excel).

One common problem is UTF-8: Excel chokes on UTF-8 encoded CSV files. Check the encoding; if you're saving the file as UTF-8, switch to standard ASCII if possible.

Another problem that could cause the issue described is if your Excel has a locale setting that uses comma as a decimal separator. This breaks Excel's ability to read a CSV file as it sees the commas as part of the field value.

Almost all the issues can be worked around by opening the file from within Excel, rather than double-clicking the file's icon. Opening a CSV file this way will cause Excel to walk you through it's text import wizard, which allows you to specify the file format so Excel will open it correctly. It's not ideal, but for some CSV files, even ones that seem like they're fairly standard (and regardless of whether they're created with PHP or not) it is the only option.

Hope that helps.