Question

Im exporting a php array to csv.

The error is that all special characters are screwed up (e.g.: á é ñ), and the start of the file displays field1 instead of field1.

The issue is happening because of Content-disposition: attachment;, if I comment that line, the file is created without any issues (sadly it is downloaded as FILENAME.php extension).

    # CSV headers
    header('Cache-Control: public');
    header('Content-Type: application/octet-stream');
    header('Content-type: application/csv; charset=utf-8');
    header('Content-disposition: attachment; filename='.date('Y-m-d H\hi').'.csv');

    # Columns
    $o = 'field1,field2,field3,field4';
    $o .= "\n";

    # Data
    $rows = array();
    foreach($data as $item) {
        $fields = array();
        foreach($item as $field) {
            $fields[] = $field;
        }
        $rows[] = implode(', ', $fields);
    }
    $o .= implode("\n", $rows);
    echo $o;

Any ideas? Thanks!

Was it helpful?

Solution

As commented by Dagon,  is the BOM and may be causing problems with the file being read (specially if it is done in CMD on Windows). Remove the BOM from your script file.

As for the special characters, you may need to convert them, specially if your source isn't UTF-8.

I had a similar problem once and the solution for me was to certify that the input was being read correctly and converting them before outputting.

For converting the characters, I did something like this:

mb_convert_case($result['products_name'], MB_CASE_UPPER, "UTF-8");

To certify I was working with UTF-8, I issued

$connection->set_charset("utf8");

when connecting to my database.

Take care.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top