Resolve PHP Export CSV Chinese garbled problem

Source: Internet
Author: User
Tags chr

garbled situation

Write a section to export the CSV file code, you can output the normal

Using 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 ');

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.