Making UTF-8 CSV for Excel

22.1.2011

Last Updated on

Sometimes you need to export a table to the Excel and other spreadsheets. CSV file saved in UTF-8 seems to be sufficiently universal format.

But there is problem with non-ASCII characters in Excel. Excel default encoding depends on the system. The workaround is to put three magical bytes to the file beginning. They are called BOM (Byte order mark) and say to the editor that file is encoded as UTF-8.

Code for the report of the assets of your company:

//headers
header('Pragma: public');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Content-Description: File Transfer');
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename=export.csv;');
header('Content-Transfer-Encoding: binary'); 

//open file pointer to standard output
$fp = fopen('php://output', 'w');

//add BOM to fix UTF-8 in Excel
fputs($fp, $bom =( chr(0xEF) . chr(0xBB) . chr(0xBF) ));
if ($fp)
{
  fputcsv($fp, array("Cars", "Planes", "Ships"), ";");
  fputcsv($fp, array("12", "2", "6"), ";");
  fputcsv($fp, array("23", "3", "5"), ";");
  fputcsv($fp, array("31", "5", "8"), ";");
}

fclose($fp);

Edit 2017-11-30: BOM does not work in older versions of Excel 2007. Try to update Excel in case of problems.

Vladislav Skoumal
SKOUMAL CEO

Comments

Author picture

Thanks Vlad, just what I was looking for all evening 🙂

Reply
Load more
Leave a comment

The Czech vocabulary-building app Vocabulary Miner created by studio SKOUMAL is based on the popular Flashcard System and special algorithm.  It promises the user to simply say more with every word and delivers it through effective, yet simple vocabulary training by ...

Read post

Listed among the best app developers in the Czech Republic, we’re excited to announce that we’ve won a 2019 Clutch leader award!   Known best as the leading platform for ratings of B2B service providers, Clutch reviews help businesses connect with the best-fit agency ...

Read post

[caption id="attachment_2730" align="aligncenter" width="1024"] Photo by Farzad Nazifi on Unsplash[/caption]   Every Android app has its unique identifier called applicationId and you have to choose it wisely because it cannot be changed later. Here are two main reasons ...

Read post

  Twitter is there to enhance your Android skills. How? Just follow the right people and get your feed updated with Android insights and hacks. If you are from the Czech Republic or Slovakia, you can be surely inspired by your local Slovak and Czech ...

Read post