How can I create a CSV file with PHP that preserves the Japanese characters?

陌路散爱 提交于 2019-12-22 07:01:57

问题


Below is my code snippet for creating and downloading the CSV file from the browser.

$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();

When I open the created/downloaded CSV file, the Japanese characters become the weird characters. What is not yet correct in my code snippet? How can I preserve the Japanese characters when creating the CSV file?


回答1:


Just add a Byte Order Mark with a simple echo directly before writing the first line if you want to force any program to interpret the file as UTF-8 encoding:

$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();

Alternatively select Unicode Character set when you import it with Excel or Open Calc, otherwise opening it directly with notepad/textedit/etc there is no problem



来源:https://stackoverflow.com/questions/32856716/how-can-i-create-a-csv-file-with-php-that-preserves-the-japanese-characters

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!