Solve the problem of garbled Chinese characters in CSV exported by PHP_PHP Tutorial

WBOY
Release: 2016-07-13 09:52:16
Original
1538 people have browsed it

Solving the Chinese garbled problem of CSV exported by PHP

The csv file can be opened with excel and performed some operations. At the same time, it is very simple for us to import the csv file with php, so we Usually php is used to export csv, but sometimes garbled characters appear when opening the csv using Excel. Let's look at the solution below.

Garbled characters

Written a piece of code to export CSV files, which can be output normally

It is normal to use CSV and TXT programs to open files, but when opening files using Excel, the problem of Chinese garbled characters appears (this is strange, why are there garbled characters in Excel?)

By checking the encoding, we found that the exported CSV file is UTF-8 without BOM encoding format, and we usually use UTF-8 encoding format with BOM.

After trying to add the BOM, the problem of Chinese garbled characters was 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);//Convert encoding

 if(fwrite($handle,$strUsersData)==false){}

fclose($handle);

 down_file($fname,'555.csv');

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/1010442.htmlTechArticleSolve the problem of Chinese garbled text exported by PHP. The csv file can be opened with excel and performed some operations. At the same time, we use php Importing csv files is very simple, so we usually use...
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!