Solve the problem of PHP exporting CSV text garbled in Chinese
CSV file can be opened with Excel and some operations, and we use PHP to import CSV file is very simple, so we usually use PHP to export CSV, but sometimes encountered in the use of Excel to open the CSV garbled problem, the following we look at the solution.
garbled situation
Write a code to export the CSV file, you can output the normal
Using CSV and TXT programs to open the file is normal, but using Excel to open the file there is a problem with Chinese garbled (this is strange, why in Excel will garbled it?)
By looking at the encoding discovery, the exported CSV file is UTF-8 no BOM encoding format, and we usually use the UTF-8 encoding format are BOM.
After trying to add a BOM, the Chinese garbled problem has been solved.
Add BOM to CSV file
Example 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);
An alternative 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);//Conversion code
if (fwrite ($handle, $strUsersData) ==false) {}
Fclose ($handle);
Down_file ($fname, ' 555.csv ');
http://www.bkjia.com/PHPjc/1010442.html www.bkjia.com true http://www.bkjia.com/PHPjc/1010442.html techarticle To solve the PHP export CSV language garbled problem csv file can be opened with Excel and some operations, while we use PHP to import CSV file is very simple, so we usually use ...