Solve the problem of Chinese garbled characters in CSV files exported by PHP
You can use excel to open a csv file and perform some operations. At the same time, it is very easy to import a csv file using php, So we usually use php to export the csv file, however, sometimes garbled characters occur when you use Excel to open csv files. Let's look at the solution below.
Garbled Information
Write a piece of code to export the CSV file, which can be output normally.
It is normal to use CSV and TXT programs to open files, but the problem of Chinese garbled characters occurs when you use Excel to open files (this is strange, why are there garbled characters in Excel ?)
By viewing the encoding, we found that the exported CSV file is a UTF-8 without BOM encoding format, and we usually use UTF-8 encoding format with BOM.
After adding BOM, the problem of Chinese garbled characters is 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 ();
}
Using fnamepolic'usersdata.csv ';
$ Handle = fopen ($ fname, 'wb ');
$ StrUsersData = iconv ('utf-8', 'gb2312', $ strUsersData); // convert the Encoding
If (fwrite ($ handle, $ strUsersData) = false ){}
Fclose ($ handle );
Down_file(%fname,'555.csv ');