【发布时间】:2011-12-21 05:43:57
【问题描述】:
我正在编写一个函数来使用 fputcsv() 处理 CSV 输出。我已经解决了很多人在使用fputcsv() 时遇到的可怕的\r\n 问题(参见代码)。
现在我试图弄清楚如何处理字段中包含的\r 或\n 字符(不是行尾返回\r\n)。在传递到fputcsv() 之前是否应该以某种方式逃脱?
该函数可以很好地处理大多数字符的转义。但是,当将 \n 插入到字段中时,MS Excel 和 Google Docs 都会出现 \n 的问题,并且 CSV 无法正确加载。
/*
* Revised Get CSV Line using PHP's fputcsv()
*
* Used to correct an issue with fputcsv()
* http://stackoverflow.com/questions/4080456/fputcsv-and-newline-codes
* MS Excel needs the MS Windows newline format of \r\n
*
*/
if (!function_exists('get_csv_line'))
{
function get_csv_line($list, $seperator = ",", $enclosure = '"', $newline = "\r\n")
{
$fp = fopen('php://temp', 'r+');
fputcsv($fp, $list, $seperator, $enclosure );
rewind($fp);
$line = fgets($fp);
if ($newline && $newline != "\n") {
if ($line[strlen($line)-2] != "\r" && $line[strlen($line)-1] == "\n") {
$line = substr_replace($line,"",-1) . $newline;
} else {
die( 'original csv line is already \r\n style' );
}
}
if ($newline == "\r\n" && substr($line, -2) != "\r\n") {
log_message('error', 'function get_csv_line: Error, needs \r\n to be MS Excel friendly!');
}
return $line;
}
}
【问题讨论】:
-
我应该用空格替换字段中的 \n 和 \r 吗?
-
我以前做过类似的事情,CSV 是一件糟糕的事情,你甚至可能会遇到诸如包含你的附件或分隔符号的字段之类的问题。我最终不得不为这些符号选择一些异国语言字符,并运行一个非常长的脚本来检查那些 \n\r 并确保有足够的封闭和分隔字符。
标签: php codeigniter csv