Today, I learned why PHP generates CSV files and garbled characters when opened in Excel. The following section describes some common methods. I hope this method will be helpful to all of you.
Baidu found out
PHP generate UTF-8 encoded CSV file with Excel open Chinese display garbled, is because the output CSV file does not have BOM.
We just need to take a look.
So how to output BOM in PHP?
Before all content is output
The Code is as follows: |
Copy code |
Print (chr (0xEF). chr (0xBB). chr (0xBF )); |
For example, we can do this when generating csv files in. php.
The Code is as follows: |
Copy code |
<? Php $ Now = gmdate ("D, d m y h: I: s "); Header ("Expires: Tue, 03 Jul 2001 06:00:00 GMT "); Header ("Cache-Control: max-age = 0, no-cache, must-revalidate, proxy-revalidate "); Header ("Last-Modified: {$ now} GMT ");
// Force download Header ("Content-Type: application/force-download "); Header ("Content-Type: application/octet-stream "); Header ("Content-Type: application/download ");
// Disposition/encoding on response body Header ("Content-Disposition: attachment; filename = {$ filename }"); Header ("Content-Transfer-Encoding: binary "); $ Items_data = array ( '0' => array ('title' => 'test test1 '), '1' => array ('title' => 'test test2 '), '2' => array ('title' => 'test test3 ') ) Print (chr (0xEF). chr (0xBB). chr (0xBF); // set UTF-8 + bom to handle garbled characters Echo array2csv ($ items_data );
Function array2csv (array & $ array) { If (count ($ array) = 0 ){ Return null; } Ob_start (); $ Df = fopen ("php: // output", 'w '); Fputcsv ($ df, array_keys (reset ($ array ))); Foreach ($ array as $ row ){ Fputcsv ($ df, $ row ); } Fclose ($ df ); Return ob_get_clean (); } ?> |
Another way is to use Office
Open Microsoft Office 2010 Excel, data-Self-text,
To import a csv file, select encoding,
Here select UTF-8, opened, found garbled elimination,
UTF-8 is the most widely used unicode encoding implementation method on the Internet. The biggest feature of UTF-8 is that it is a variable length encoding method. It can use 1 ~ Four bytes indicate one symbol, and the length of the byte varies according to different symbols.