YesItsMe
YesItsMe

Reputation: 1779

Export to csv with BOM, Strange space begining of document that makes trouble

In order to get excel to read csv document properly without converting it to ASCII characters you need to have a UTF-8 BOM (3 bytes, hex EF BB BF) at the start of the file.

this is the function I use to export to csv

    function download_csv_results($results, $name)
    {   
        header('Content-Type: text/csv; charset=utf-8');
        header("Content-Transfer-Encoding: UTF-8");
        header('Content-Disposition: attachment; filename='. $name);
        header('Pragma: no-cache');
        header("Expires: 0");
        $outstream = fopen("php://output", "w");
fwrite($outstream, "\xEF\xBB\xBF");
         fputcsv($outstream, array_keys($results[0]));



        foreach($results as $result)
        {
            fputcsv($outstream, $result);
        }

        fclose($outstream);
    }

The issue is when i view it in hex I see

20 ef bb bf

as opposed to

ef bb bf 20

I think 20 is a space but what causes that space, and why it's at the beginning of document is what I can't figure out.

Upvotes: 1

Views: 383

Answers (1)

YesItsMe
YesItsMe

Reputation: 1779

Based on this answer I figured it out i had a space at the begining of the file " <?php" for some reason it was included in the document I would appreciate if someone could explain to me why it was included.

Upvotes: 1

Related Questions