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

如何使用PHP创建保留日语字符的CSV文件?,php,csv,character-encoding,character,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');

下面是我从浏览器创建和下载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编码,请在写入第一行之前直接添加一个带有简单回波的字节顺序标记:

$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导入Unicode字符集或打开Calc时,选择
Unicode字符集
,否则直接使用记事本/textedit/etc打开不会有问题

它可以完美地运行您的代码,我看不出有任何问题:以下是下载的CSV文件的结果:
注文日時,受注番号 2015-09-30,INV-00001
我注意到excel在这里是个混蛋,标准文本编辑器很好。编辑:请参阅是否有方法在不在Excel或Open Calc上选择的情况下使用选定的正确Unicode字符集创建CSV,因为我的用户不知道他们需要这样做。是否有方法在不在Excel或Open Calc上选择的情况下使用选定的正确Unicode字符集创建CSV,因为我的用户不知道他们需要这样做。是的,字节顺序标记发挥了神奇的作用。非常感谢加布里埃尔·罗德里格斯。你刚刚救了我的命。很高兴知道这一点!。。。你的祝福也拯救了我的一天。。谢谢你@GabrielRodriguez:)欢迎你@AirfulShishir我不记得这个lol…我完全忘记了这个(这些天有这么多信息)如果有一天我想这样做,我可能会在网上找到我自己的答案,因为那时我可能会忘记它lol。。。