php fputcsv garbled solution: 1. Place the header function before fopen; 2. Directly output to the browser through "fopen('php://output', 'a');" 3. , just add bom at the beginning of the first string written.
The operating environment of this article: Windows7 system, PHP7.1 version, DELL G3 computer
How to solve php fputcsv garbled characters Problem?
PHP uses fputcsv() to generate a csv file and open it under Windows Excel to solve the problem of garbled characters
The csv file opens normally under windows wps and my ubuntu16 desktop version.
But using windows Excel opens garbled characters.
Solution:
function test() { $fileName = 'demo'; // 几个header函数需要放fopen之前。不然会直接在浏览器页面打印输出。而不是文件下载 header('Content-Type: application/vnd.ms-excel'); header('Content-Disposition: attachment;filename="'.$fileName.'.csv"'); header('Cache-Control: max-age=0'); //直接输出到浏览器 $fp = fopen('php://output', 'a'); //在写入的第一个字符串开头加 bom。 $bom = chr(0xEF).chr(0xBB).chr(0xBF); $column = [ $bom.'姓名','性别', '年龄' ]; $data = [ '张三','男士', '21' ]; fputcsv($fp, $column); fputcsv($fp, $data); fclose($fp);}
Recommended study: "PHP Video Tutorial"
The above is the detailed content of How to solve the garbled problem of php fputcsv. For more information, please follow other related articles on the PHP Chinese website!