【问题标题】:Adding BOM to CSV file using fputcsv使用 fputcsv 将 BOM 添加到 CSV 文件
【发布时间】:2014-10-30 10:13:02
【问题描述】:

我正在生成一个包含外来字符的简单 CSV 文件。我注意到,如果我不包含字节顺序标记,则外来字符在 Excel 中无法正确显示(但在存在 BOM 时它们看起来很好)。

如何在第一次创建文件时将 BOM 添加到文件的开头?我尝试了以下方法,但它不起作用:-/

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 在您的fopen() 之后立即添加到文件中(尽管在您的追加中不是一个好主意)....不要使用fputcsv() 尝试编写它跨度>
  • @MarkBaker 如果您想将其放入答案中,我会接受。它奏效了。否则我以后再做。告诉我。

标签: php excel csv byte-order-mark fputcsv


【解决方案1】:

感谢Mark Baker 的回答:

我需要使用 fwrite() 添加 BOM,而不是 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;
    } 
}

谢谢,马克!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-29
    相关资源
    最近更新 更多