I am writing a function to handle CSV output using fputcsv() . I worked on the \r\n problem that so many people had with fputcsv() (see Code).
Now I'm trying to figure out how to handle the characters \r or \n that are included in the field (and not the end of the string returns \r\n ). Should he somehow escape before going into fputcsv() ?
The function handles escaping for most characters. But, when a \n inserted into the field, both MS Excel and Google Docs have problems with \n , and CSV cannot load correctly.
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; } }
source share