The csv file can be opened with excel and performed some operations. At the same time, it is very simple for us to import the csv file with php, so we Usually php is used to export csv, but sometimes garbled characters appear when opening the csv using Excel. Let's look at the solution below.
Garbled characters
Written a piece of code to export CSV files, which can be output normally
It is normal to use CSV and TXT programs to open files, but when opening files using Excel, the problem of Chinese garbled characters appears (this is strange, why are there garbled characters in Excel?)
By checking the encoding, we found that the exported CSV file is UTF-8 without BOM encoding format, and we usually use UTF-8 encoding format with BOM.
After trying to add the BOM, the problem of Chinese garbled characters was solved.
Add BOM to CSV file
Sample code:
$file = fopen($export_file_path, 'w');
fwrite($file, chr(0xEF).chr(0xBB).chr(0xBF)); // Add BOM
foreach ($contens as $content) {
fputcsv($file, $content);
}
fclose($file);
Another solution
Function down_file($filepath,$filename)
{
if(!file_exists($filepath))
{
echo "backup error ,download file no exist";
exit();
}
ob_end_clean();
header('Content-Type: application/download');
header("Content-type: text/csv");
header('Content-Disposition: attachment;filename="'.$filename.'"');
header("Content-Encoding: binary");
header("Content-Length:".filesize($filepath));
header("Pragma: no-cache");
header("Expires: 0");
readfile($filepath);
$e=ob_get_contents();
ob_end_clean();
}
$fname='usersdata.csv';
$handle=fopen($fname,'wb');
$strUsersData =iconv('utf-8','gb2312',$strUsersData);//Convert encoding
if(fwrite($handle,$strUsersData)==false){}
fclose($handle);
down_file($fname,'555.csv');