Solve the problem of Chinese garbled characters in CSV files exported by PHP

Source: Internet
Author: User

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

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.