Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 350
O Connor Avatar asked Sep 30 '15 02:09

O Connor


1 Answers

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 Importing

like image 102
Gabriel Rodriguez Avatar answered Nov 14 '22 22:11

Gabriel Rodriguez