使用fputcsv将BOM添加到CSV文件 [英] Adding BOM to CSV file using fputcsv
本文介绍了使用fputcsv将BOM添加到CSV文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在生成一个包含外来字符的简单CSV文件.我注意到,如果我不包含字节顺序标记,则表示外来字符在Excel中无法正确显示(但是当存在BOM表时,外来字符会很好显示).
I have a simple CSV file being generated that includes foreign characters. I've noted that if I don't include a Byte Order Mark that the foreign characters aren't appearing properly in Excel (but they appear fine when a BOM is present).
如何在第一次创建BOM表时将其添加到文件的开头?我尝试了以下方法,但它不起作用:-/
How can I add a BOM to the beginning of the file when it's first created? I've tried the following and it's not working :-/
function processForm($competition, $competitionEntry) {
$BOM = "\xEF\xBB\xBF"; // UTF-8 BOM
$filename = $competition->ID.".csv";
$file = "entries/".$filename;
$fields = array_keys($competitionEntry);
$submittedForm = $competitionEntry;
if(file_exists($file)) {
$fp = fopen($file, 'a');
if($fp &&
fputcsv($fp, $submittedForm) &&
fclose($fp)) {
return true;
}
} else { // CREATE NEW FILE
$fp = fopen($file, 'w');
if($fp &&
fputcsv($fp, $BOM) && // WRITE BOM TO FILE
fputcsv($fp, $fields) &&
fputcsv($fp, $submittedForm) &&
fclose($fp)) {
return true;
}
}
return false;
}
推荐答案
感谢马克·贝克的回答:
我需要使用fwrite()添加BOM,而不是fputcsv().
I needed to use fwrite() to add the BOM, not fputcsv().
工作版本如下:
if(file_exists($file)) {
$fp = fopen($file, 'a');
if($fp &&
fputcsv($fp, $submittedForm) &&
fclose($fp)) {
return true;
}
} else {
$fp = fopen($file, 'w');
fwrite($fp, $BOM); // NEW LINE
if($fp &&
fputcsv($fp, $fields) &&
fputcsv($fp, $submittedForm) &&
fclose($fp)) {
return true;
}
}
谢谢,马克!
这篇关于使用fputcsv将BOM添加到CSV文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文