如何使用PHP创建保留日文字符的CSV文件?

时间:2015-09-30 02:19:51

标签: php csv character-encoding character

以下是我从浏览器创建和下载CSV文件的代码段。

$input_array[] = ['注文日時', '受注番号',];
$input_array[] = ['2015-09-30', 'INV-00001',];

    /** open raw memory as file, no need for temp files, be careful not to run out of memory thought */
    $f = fopen('php://memory', 'w');
    /** loop through array  */
    foreach ($input_array as $line) {
        /** default php csv handler **/
        fputcsv($f, $line, ',');
    }
    /** rewrind the "file" with the csv lines **/
    fseek($f, 0);

    /** modify header to be downloadable csv file **/
    header('Content-Encoding: UTF-8');
    header('Content-Type: application/csv; charset=UTF-8');
    header('Content-Disposition: attachement; filename="my_csv_file.csv";');

    /** Send file to browser for download */
    fpassthru($f);

    die();

当我打开创建/下载的CSV文件时,日文字符变成了奇怪的字符。我的代码段中还有什么不正确?如何在创建CSV文件时保留日文字符?

1 个答案:

答案 0 :(得分:6)

如果要强制任何程序将文件解释为UTF-8编码,只需在编写第一行之前直接添加带简单echo的字节顺序标记:

$input_array[] = ['注文日時', '受注番号',];
$input_array[] = ['2015-09-30', 'INV-00001',];
echo "\xEF\xBB\xBF";/// Byte Order Mark HERE!!!!

    /** open raw memory as file, no need for temp files, be careful not to run out of memory thought */
    $f = fopen('php://memory', 'w');
    /** loop through array  */
    foreach ($input_array as $line) {
        /** default php csv handler **/
        fputcsv($f, $line, ',');
    }
    /** rewrind the "file" with the csv lines **/
    fseek($f, 0);

    /** modify header to be downloadable csv file **/
    header('Content-Encoding: UTF-8');
    header('Content-Type: application/csv; charset=UTF-8');
    header('Content-Disposition: attachement; filename="my_csv_file.csv";');

    /** Send file to browser for download */
    fpassthru($f);

    die();

或者当你用Excel或Open Calc导入它时选择Unicode Character set,否则直接用notepad / textedit / etc打开它没有问题 Importing