写入csv文件时转义分号字符

时间:2011-12-14 08:55:41

标签: php csv

我想写点像

=HYPERLINK("http://example.com"; "Example")

以逗号分隔的CSV文件,但Excel解析分号并将“Example”部分放在另一个单元格中。我尝试用反斜杠转义分号并用双引号括起所有内容而没有任何运气。

任何帮助?

3 个答案:

答案 0 :(得分:25)

使用双引号包装已经是正确的想法,但您必须确保正确执行。您可以将列放在双引号内,然后将内部的所有内容视为单个值。引用本身必须通过编写其中两个("")来转义。

例如见:

Column A;Column B;Column C
Column A;"Column B; with semicolon";Column C
Column A;"Column B"";"" with semicolon and quotes";Column C
Column A;"=HYPERLINK(""http://example.com""; ""Example"")";Column C

答案 1 :(得分:3)

我还有一个非常狂野的时间来弄清楚整个画面,然后就是我如何让我的所有csv准备好在php中打开excel(其中包括utf8编码):

$sep='";"';//note the separator is double quoted
while($t=mysql_fetch_assoc(mysql_query('select ..')){
  #replaces the caracters who are breaking csv display
  $t=array_map(function($x){return str_replace(array("\n","\r",'"'),array('\\n',"\\r",'""'),$x);},$t);
  $csv.="\n\"".implode($sep,$t)."\"";
}
$charset='utf-8';
header('Content-Type: application/csv;charset='.$charset);
header('Content-Disposition: attachment; filename="filename.csv"');
$bom=chr(239).chr(187).chr(191);#this tells excel document is utf8 encoded
die($bom.$csv);

答案 2 :(得分:0)

我对每个CSV值使用此函数来正确传递它。仅当它包含新行符号,双引号或分隔符时才引用值。实际上,唯一要逃避的值是双引号符号。所有其他单元格内容都会进入并在Excel中正确显示。

使用Windows下的西里尔语言环境中的各种版本的Excel和ODBC CSV解析器进行检查。

/**
 * This function escapes single CSV value if it contains new line symbols, quotes or separator symbol and encodes it into specified $encoding.
 * 
 * @param string $source - origin string
 * @param string $sep - CSV separator
 * @param string $source_encoding - origin string encoding
 * @param string $encoding - destination encoding
 *
 * @return string - escaped string, ready to be added to CSV
 *
 * @example echo escapeStringCSV("Hello\r\n\"World\"!");
 *  will output
 *      "Hello
 *      ""World""!"
 */
function escapeStringCSV($source, $sep=';', $source_encoding='utf-8', $encoding="windows-1251//TRANSLIT"){

    $str = ($source_encoding!=$encoding ? iconv($source_encoding, $encoding, $source) :  $source);

    if(preg_match('/[\r\n"'.preg_quote($sep, '/').']/', $str)){
        return '"'.str_replace('"', '""', $str).'"';
    } else 
        return $str;
}

所以用法可以是这样的:

 while($row = mysql_fetch_assoc($res)){
    foreach($row as $val){
        $csv .= escapeStringCSV($val).';';
    }
    $csv .= "\r\n";
}  
相关问题