php generates csv garbled characters because the output csv format file does not have a BOM. The solution is to use the BOM to indicate the character encoding, with a code such as "header("Content-type:text/csv;charset=gb2312"); ".
The operating environment of this article: windows7 system, PHP7.1 version, DELL G3 computer
Solution to the Chinese garbled Chinese code in PHP output csv file
PHP download files often use byte stream output. Therefore, the commonly used codes for downloading csv format are as follows:
header("Content-Type: application/force-download"); header("Content-type:text/csv;charset=gb2312"); header("Content-Disposition:filename=打开邮件导出".date("YmdHis").".csv"); echo "收件人邮箱,收件人姓名,发送时间\r"; ob_end_flush(); foreach($list as $rs) { echo $rs->toemail.",".$rs->name.",".date('Y-m-d H:i:s',$rs->addtime)."\r"; flush(); } exit;
It is normal for the csv file downloaded in this way to be opened with an editor such as Notepad or sublime text, but it will be garbled when opened with excel because the output csv format file is There is no BOM, and there are many opinions about BOM. Under normal circumstances, BOM needs to be removed in PHP, but csv files need to use BOM marking character encoding.
The solution is as follows:
header("Content-Type: application/force-download"); header("Content-type:text/csv;charset=gb2312"); header("Content-Disposition:filename=打开邮件导出".date("YmdHis").".csv"); echo chr(0xEF).chr(0xBB).chr(0xBF); echo "收件人邮箱,收件人姓名,发送时间\r"; ob_end_flush(); foreach($list as $rs) { echo $rs->toemail.",".$rs->name.",".date('Y-m-d H:i:s',$rs->addtime)."\r"; flush(); } exit;
Due to the difference between the line breaks in Linux and window. If the above code has a bad reaction in the Linux server, you can change "\r" to "\r\n".
Recommended learning: "PHP Video Tutorial"
The above is the detailed content of What to do if php generates csv garbled characters. For more information, please follow other related articles on the PHP Chinese website!