When creating a CSV file, how do I handle \n and \r characters in a field?

21,958

If there are \r or \n within the field just make sure the entire field is enclosed by double quotes (and that literal double quotes are double-double quoted)

So for a final result of

value1,"so this is a
multiline value",value2

where 'a' and 'multiline' are separated by either a \n or \r (remember, \r wont show up on excel, but its there), then it should have worked.

If the \n or \r values are embedded in the values you have in the PHP array, then it should already be enclosed appropriately.

Share:
21,958
jjwdesign
Author by

jjwdesign

LAMP Developer, Designer, etc.

Updated on October 12, 2020

Comments

  • jjwdesign
    jjwdesign over 3 years

    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;
        }
    }