Home  >  Article  >  Backend Development  >  How to solve the php csv garbled problem

How to solve the php csv garbled problem

藏色散人
藏色散人Original
2020-08-22 10:37:561956browse

php csv乱码的解决办法:首先重写fputcsv方法;然后添加转码功能,代码如“function fputcsv2($handle, array $fields, $delimiter = "){...}”。

How to solve the php csv garbled problem

推荐:《PHP视频教程

PHP导出CSV中文乱码的解决方法:UTF-8转GB2312

一、背景

因项目需求,要导出Excel表格数据,使用fputcsv方法导出数据遇到中文乱码,去网上查找了一遍解决方法。

1)设置header编码修改为UTF-8

2)在输出内容前先输出BOM头

以上两种方法均无效,不知是否我的环境原因还是其他,暂不去深究。

二、解决方法

由于项目默认是UTF-8编码,Excel不支持,所以得把UTF-8转GB2312。

【核心】重写fpucsv方法,添加转码功能:

/**
 * 重写fputcsv方法,添加转码功能
 * @param $handle
 * @param array $fields
 * @param string $delimiter
 * @param string $enclosure
 * @param string $escape_char
 */
function fputcsv2($handle, array $fields, $delimiter = ",", $enclosure = '"', $escape_char = "\\") {
    foreach ($fields as $k => $v) {
        $fields[$k] = iconv("UTF-8", "GB2312//IGNORE", $v);  // 这里将UTF-8转为GB2312编码
    }
    fputcsv($handle, $fields, $delimiter, $enclosure, $escape_char);
}

使用例子:

function test () {
    // 文件名
    $filename = "订单查询结果" . date('Y-m-d H:i:s');
 
    // 设置输出头部信息
    header('Content-Encoding: UTF-8');
    header("Content-Type: text/csv; charset=UTF-8");
    header("Content-Disposition: attachment; filename={$filename}.csv");
 
 
    $tableHead = array('#', '订单id', '订单号', '分类', '客户信息', '工匠信息', '订单状态', '施工状态', '付款状态', '订单金额', '下单时间', '备注');
 
    // 获取句柄
    $output = fopen('php://output', 'w') or die("can't open php://output");
 
    // 输出头部标题
    fputcsv2($output, $tableHead);
 
    $list = array();
    foreach ($list as $item) {
        fputcsv2($output, array_values($item));
    }
 
    // 关闭句柄
    fclose($output) or die("can't close php://output");
}

The above is the detailed content of How to solve the php csv garbled problem. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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