CSV files can be opened with Excel and do some work, and we use PHP to import a CSV file is very simple, so we usually use PHP to export CSV, but sometimes encountered in the use of Excel to open a CSV when the garbled problem, the following we see the solution.
garbled situation
Write a section to export the CSV file code, you can output the normal
The use of CSV and TXT program to open the file is normal, but the use of Excel to open the file appears in the Chinese garbled problem (this is strange, why in Excel will garbled it?)
By looking at the encoding discovery, the exported CSV file is UTF-8 without a 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
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).//Conversion encoding
if (fwrite ($handle, $strUsersData) ==false) {}
Fclose ($handle);
Down_file ($fname, ' 555.csv ');