How to solve the garbled problem of php fputcsv

藏色散人
Release: 2023-03-12 13:36:01
Original
2467 people have browsed it

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.

How to solve the garbled problem of php fputcsv

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);}
Copy after login

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!

Related labels:
php
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!