如何使用PHP创建一个保留日语字符的CSV文件? [英] How can I create a CSV file with PHP that preserves the Japanese characters?
问题描述
下面是我用于从浏览器创建和下载CSV文件的代码段.
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();
当我打开创建/下载的CSV文件时,日语字符变成了奇怪的字符.我的代码段中还不正确的地方是什么?创建CSV文件时如何保留日语字符?
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?
推荐答案
如果要强制任何程序将文件解释为UTF-8,只需在写第一行之前直接添加带有简单echo
的字节顺序标记编码:
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();
或者使用Excel或Open Calc导入Unicode Character set
时,也可以选择Unicode Character set
,否则直接使用notepad/textedit/etc打开它就没有问题
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
这篇关于如何使用PHP创建一个保留日语字符的CSV文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!