How to Export UTF-8 CSV File in PHP

I had problems with displaying UTF-8 characters in my exported CSV files. Unlike LibreOffice Calc and Google Docs, this happened on only MS Excel. Here is a small hack:

header("Content-Transfer-Encoding: binary");
header("Content-Length: " . strlen($str) ."; ");
header("Content-Disposition: attachment; filename=\"ourfilename.csv\"; ");
header("Content-Type: application/vnd.ms-excel");
echo "\xEF\xBB\xBF"; // UTF-8 BOM
echo $str;

Add new comment

Filtered HTML

  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <blockquote> <code> <ul> <ol> <li> <dl> <dt> <dd>
  • Lines and paragraphs break automatically.

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.
CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
3 + 0 =
Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.