title: When creating a CSV file, how do I handle \n and \r characters in a field?
body: <p>I am writing a function to handle CSV output using <a href="http://www.php.net/manual/en/function.fputcsv.php" rel="noreferrer"><code>fputcsv()</code></a>. I've worked around the dreaded <code>\r\n</code> issue that so many people have had with <code>fputcsv()</code> (see code).</p>
  
  <p>Now I'm trying to figure out how to handle <code>\r</code> or <code>\n</code> characters that are included in a field (not the line ending returns <code>\r\n</code>). Should it be escaped somehow before being passed into <code>fputcsv()</code>? </p>
  
  <p>The function handles escaping well for most characters. But, when a <code>\n</code> is inserted into a field, both MS Excel and Google Docs have problems with the <code>\n</code> and the CSV fails to load properly.</p>
  
  <pre><code>/*
  * 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 &amp;&amp; $newline != "\n") {
              if ($line[strlen($line)-2] != "\r" &amp;&amp; $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" &amp;&amp; substr($line, -2) != "\r\n") {
              log_message('error', 'function get_csv_line: Error, needs \r\n to be MS Excel friendly!');
          }
          return $line;
      }
  }
  </code></pre>