Export UTF-8 data in excel with correct encoding

/ Published in: PHP
Save to your folder(s)

If you want to export some utf-8 data into csv/tsv that will be readable by excel with correct encoding you must add special non vissable characters at the begining of file

Copy this code and paste it in your HTML
  1. <?php
  3. $data = "Some utf-8 characters ąćżźćł"
  5. header("Content-Type: application/octet-stream");
  6. header("Content-Transfer-Encoding: binary");
  7. header('Expires: '.gmdate('D, d M Y H:i:s').' GMT');
  8. header('Content-Disposition: attachment; filename = "Export '.date("Y-m-d").'.tsv"');
  9. header('Pragma: no-cache');
  11. //these characters will make correct encoding to excel
  12. echo chr(255).chr(254).iconv("UTF-8", "UTF-16LE//IGNORE", $data);
  14. ?>

URL: http://www.php.net/manual/en/function.iconv.php#104287

Report this snippet


RSS Icon Subscribe to comments

You need to login to post a comment.