I am writing a function to handle CSV output using fputcsv()
. I've worked around the dreaded \r\n
issue that so many people have had with fputcsv()
(see code).
Now I'm trying to figure out how to handle \r
or \n
characters that are included in a field (not the line ending returns \r\n
). Should it be escaped somehow before being passed into fputcsv()
?
The function handles escaping well for most characters. But, when a \n
is inserted into a field, both MS Excel and Google Docs have problems with the \n
and the CSV fails to load properly.
/*
* 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;
}
}