Solve the problem of Chinese garbled characters in CSV files exported by PHP. To solve the problem of Chinese garbled characters in exported CSV files in PHP, you can use excel to open the csv files and perform some operations. at the same time, it is very easy to import csv files using php, therefore, we usually use PHP to export CSV files with Chinese garbled characters.
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 ');
You can use excel to open the csv file and perform some operations. at the same time, it is very easy to import the csv file using php, so we usually use...