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

标签 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 文件时如何保留日语字符?

最佳答案

如果您想强制任何程序将文件解释为 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等打开是没有问题的 Importing

关于php - 如何使用 PHP 创建保留日文字符的 CSV 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32856716/

相关文章:

mysql - Primefaces ajax 字符集

Javascript 编码

php - 在mysql查询中转换字符集

php - CRC 16 -DECT 与聚 x^16 + x^10 + x^8 + x^7 + x^3 + 1

php - 我无法在 PHPmyadmin XAMPP 中设置外键

PHP + 将多行从 .csv 保存到 mysql

xml - 从 XSL 输出中删除空行

php - 无法弄清楚如何使用 Docker 容器启动 PHP-FPM

php - 如何将 GROUP_BY 与查询构建器和 mySQL >= 5.7 一起使用?

python - 访问从 CSV 文件读取的行时列表索引超出范围