下面是我用于从浏览器创建和下载 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 编码,只需在写入第一行之前直接添加一个带有简单 echo
的字节顺序标记:
$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
,否则直接用notepad/textedit等打开是没有问题的
关于php - 如何使用 PHP 创建保留日文字符的 CSV 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32856716/