This article mainly introduces php to generate csv garbled code under mac. It has a certain reference value. Now I share it with everyone. Friends in need can refer to it
<?php $file_name = date('Ymd', time()) . '.csv'; //设置文件名 header('Content-Type: application/vnd.ms-excel'); header('Content-Disposition: attachment;filename='.$file_name); header('Cache-Control: max-age=0'); $fp = fopen('php://output', 'a'); $row = [ 'name' => '测试', 'email' => 111111, 'mobile' => 22222, 'weixinid' => '微信号', ]; fwrite($fp,"\xEF\xBB\xBF"); fputcsv($fp, $row);
Solution to the garbled problem of php exporting csv files
Before talking about this question, let’s first talk about what is a CSV file? Comma Separator Value (comma separated value) is also. Intermediate files that are often used for data conversion exist, such as exporting data from Mysql to CSV and importing CSV into SqlServer. Use a PHP script under Linux to export the table data from the Mysql database into csv according to conditions. Use utf-8 encoding to export the CSV file. After opening, the Chinese inside becomes garbled (CSV files under Windows are associated with Microsoft Excel by default). Use Notepad or Word opens normally, but the layout is messy. Reason: BOM is in trouble, Microsoft is in trouble.
What is BOM? Byte Order Mark (bit order mark) is also.
In order to identify Unicode files, Microsoft recommends that all Unicode files should start with ZERO WIDTH NOBREAK SPACE characters. This serves as a "signature" or "byte-order mark (BOM)" to identify the encoding and byte order (big-endian or little-endian) used in the file. The specific correspondence is shown in the table below .
Bytes Encoding Form
UTF-32, big-endian | |
UTF-32, little-endian | |
UTF-16, big-endian | |
UTF-16, little-endian | |
UTF-8 |
BOM is not used in Unix-like systems because it will break the existing ASCII file syntax convention.
Note: When writing the csv file, ensure that the php source code is utf-8, has no BOM, and does not output anything.
PHP generates a unique RequestID class
Detailed example of how to generate a .csv suffix file table in PHP
The above is the detailed content of PHP generates csv with garbled characters under mac. For more information, please follow other related articles on the PHP Chinese website!