创建CSV文件时,如何处理字段中的\n和\ r \n字符?

jjw*_*ign 7 php csv codeigniter

我正在编写一个函数来处理CSV输出fputcsv().我已经解决了\r\n许多人曾经遇到的可怕问题fputcsv()(见代码).

现在我想弄清楚如何处理\r\n字段中包含的字符(不是行结束返回\r\n).是否应该在被传递之前以某种方式逃脱fputcsv()

该函数可以很好地处理大多数字符的转义.但是,当a \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;
    }
}
Run Code Online (Sandbox Code Playgroud)

arc*_*rty 4

如果字段中有 \r 或 \n,只需确保整个字段用双引号括起来(并且文字双引号是双双引号)

所以对于最终结果

value1,"so this is a
multiline value",value2
Run Code Online (Sandbox Code Playgroud)

其中 'a' 和 'multiline' 由 \n 或 \r 分隔(记住,\r 不会出现在 Excel 上,但它在那里),那么它应该可以工作。

如果 \n 或 \r 值嵌入到 PHP 数组中的值中,那么它应该已经被适当地括起来。