Home » excel » excel – Export CSV by PHP for utf-8 characters

excel – Export CSV by PHP for utf-8 characters

Posted by: admin April 23, 2020 Leave a comment

Questions:

I need to export a .csv file with php. I used below code to do that:

header('Content-Encoding: UTF-8');
header('Content-type: application/csv; charset=UTF-8');
header("Content-Disposition: attachment; filename=$fn");
echo "\xEF\xBB\xBF"; // UTF-8 BOM
print($csv); 

$csv contains some persian characters. When i opened the exported file with ms excel, wrong characters showed. When i opened file with notepad characters showed right.
how can i solve this problem?

How to&Answers:

Here’s how I did it.

header('Content-Encoding: UTF-8');
header('Content-type: text/csv; charset=UTF-8');
header("Content-Disposition: attachment; filename=file.csv");
header("Pragma: no-cache");
header("Expires: 0");
header('Content-Transfer-Encoding: binary');
echo "\xEF\xBB\xBF";

Earlier i was getting garbage characters now correct data is exported.