Home  >  Article  >  Backend Development  >  What to do if php generates csv garbled characters

What to do if php generates csv garbled characters

藏色散人
藏色散人Original
2021-05-18 09:42:212910browse

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"); ".

What to do if php generates csv garbled characters

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn