简体   繁体   English

PHP导出CSV文件

[英]PHP export csv file

I am trying to export csv file but when i export file it generates chienese text in csv. 我正在尝试导出csv文件,但是当我导出文件时,它会在csv中生成中文文本。

public function actionExportFile()
{
       header('Content-Type: text/csv; charset=utf-8');
       $list = array (
                array('aaa', 'bbb', 'ccc', 'dddd'),
                array('123', '456', '789'),
                array('"aaa"', '"bbb"')
                );

                $fp = fopen('file.csv', 'w');

                foreach ($list as $fields) {
                    fputcsv($fp, $fields);
                }

                fclose($fp);
        exit;
    }

What i am doing wrong to export csv. 我在做错出口CSV。

You seem to be mixing 2 uses of PHP with header and file writing. 您似乎在混合使用PHP和标题和文件两种方式。 Either remove the header line to write to a file on the server : 删除header行以写入服务器上的文件:

function actionExportFile()
{
   $list = array (
            array('aaa', 'bbb', 'ccc', 'dddd'),
            array('123', '456', '789'),
            array('"aaa"', '"bbb"')
            );

            $fp = fopen('file.csv', 'w');

            foreach ($list as $fields) {
                fputcsv($fp, $fields);
            }

            fclose($fp);
    exit;
}

or change your code to: 或将您的代码更改为:

function actionExportFile()
{
   header('Content-Type: text/csv; charset=utf-8');
   $list = array (
            array('aaa', 'bbb', 'ccc', 'dddd'),
            array('123', '456', '789'),
            array('"aaa"', '"bbb"')
            );

            foreach ($list as $fields) {
            echo implode( ',', $fields );
         }
    exit;
}

to produce a file download. 产生文件下载。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM