Home  >  Article  >  PHP Framework  >  What to do if the csv file exported by yii2 is garbled?

What to do if the csv file exported by yii2 is garbled?

尚
Original
2020-01-13 15:10:342139browse

What to do if the csv file exported by yii2 is garbled?

yii exports the CSV code as follows:

/**
 * 导出csv
 * @author yhdsir
 * @param array    $parameter header 表头
 * @param array    $parameter data   数据
 * @param string   $filename         导出名字
 */
public function export($parameter, $filename = '')
{
    if (empty($filename)) {
        $filename = date('Y-m-d_H-i-s');
    }

    $filename = str_replace(array('"', "'", ' ', ','), '_', $filename) . '.csv';

    if (is_array($parameter)) {
        header('Content-Type: application/vnd.ms-excel');
        header('Cache-Control: max-age=0');
        header("Content-Disposition: attachment;filename={$filename}");
        $fp = fopen('php://output', 'w');
        //fwrite($fp, chr(0xEF) . chr(0xBB) . chr(0xBF));  // 添加 BOM
        if (!empty($parameter['header']) && is_array($parameter['header'])) {
            foreach ($parameter['header'] as $i => $v) {
                // CSV的Excel支持GBK编码,一定要转换,否则乱码 
                // $head[$i] = iconv('utf-8', 'gbk', $v); 
                $parameter['header'][$i] = iconv('utf-8', 'gb2312//TRANSLIT//IGNORE', $v);
            }
            // 将数据通过fputcsv写到文件句柄 
            fputcsv($fp, $parameter['header']);
        }
        if (isset($parameter['data'])) {
            foreach ($parameter['data'] as $row) {
                foreach ($row as $i => $v) {
                    $row[$i] = iconv('utf-8', 'gb2312//TRANSLIT//IGNORE', $v);
                }
                fputcsv($fp, $row);
            }
        }
        fclose($fp);

        return true;
    }
    throw new \yii\web\HttpException(500, "Not a valid parameter!");
}

iconv - The string is converted according to the required character encoding

Instructions

iconv ( string $in_charset , string $out_charset , string $str ) : string

Convert string str from in_charset to out_charset.

Parameters

in_charset: Input character set.

out_charset: Output character set.

str: ​​The string to be converted.

Return value: Returns the converted string, or returns FALSE on failure.

Recommended learning: yii tutorial

The above is the detailed content of What to do if the csv file exported by yii2 is garbled?. 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