fputcsv and newline codes fputcsv and newline codes php php

fputcsv and newline codes


// Writes an array to an open CSV file with a custom end of line.//// $fp: a seekable file pointer. Most file pointers are seekable, //   but some are not. example: fopen('php://output', 'w') is not seekable.// $eol: probably one of "\r\n", "\n", or for super old macs: "\r"function fputcsv_eol($fp, $array, $eol) {  fputcsv($fp, $array);  if("\n" != $eol && 0 === fseek($fp, -1, SEEK_CUR)) {    fwrite($fp, $eol);  }}


This is an improved version of @John Douthat's great answer, preserving the possibility of using custom delimiters and enclosures and returning fputcsv's original output:

function fputcsv_eol($handle, $array, $delimiter = ',', $enclosure = '"', $eol = "\n") {    $return = fputcsv($handle, $array, $delimiter, $enclosure);    if($return !== FALSE && "\n" != $eol && 0 === fseek($handle, -1, SEEK_CUR)) {        fwrite($handle, $eol);    }    return $return;}


Using the php function fputcsv writes only \n and cannot be customized. This makes the function worthless for microsoft environment although some packages will detect the linux newline also.

Still the benefits of fputcsv kept me digging into a solution to replace the newline character just before sending to the file. This can be done by streaming the fputcsv to the build in php temp stream first. Then adapt the newline character(s) to whatever you want and then save to file. Like this:

function getcsvline($list,  $seperator, $enclosure, $newline = "" ){    $fp = fopen('php://temp', 'r+');     fputcsv($fp, $list, $seperator, $enclosure );    rewind($fp);    $line = fgets($fp);    if( $newline and $newline != "\n" ) {      if( $line[strlen($line)-2] != "\r" and $line[strlen($line)-1] == "\n") {        $line = substr_replace($line,"",-1) . $newline;      } else {        // return the line as is (literal string)        //die( 'original csv line is already \r\n style' );      }    }        return $line;}/* to call the function with the array $row and save to file with filehandle $fp */$line = getcsvline( $row, ",", "\"", "\r\n" );fwrite( $fp, $line);