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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With