note 14788 modified in function.fgetcsv by danbrown

From: Date: Sun, 17 May 2009 18:25:17 +0000
Subject: note 14788 modified in function.fgetcsv by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-155112@lists.php.net to get a copy of this message
Here is a function that takes an array and adds a CSV line to the passed file pointer. <?php function fputcsv ($fp, $array, $deliminator=",") { $line = ""; foreach($array as $val) { # remove any windows new lines, # as they interfere with the parsing at the other end $val = str_replace("\r\n", "\n", $val); # if a deliminator char, a double quote char or a newline # are in the field, add quotes if(ereg("[$deliminator\"\n\r]", $val)) { $val = '"'.str_replace('"', '""', $val).'"'; }#end if $line .= $val.$deliminator; }#end foreach # strip the last deliminator $line = substr($line, 0, (strlen($deliminator) * -1)); # add the newline $line .= "\n"; # we don't care if the file pointer is invalid, # let fputs take care of it return fputs($fp, $line); }#end fputcsv() ?> [EDIT BY danbrown AT php DOT net: A function named fputcsv(), performing a very similar action, was added to the core in PHP 5.1.0.] --was-- Here is a function that takes an array and adds a CSV line to the passed file pointer. <?php function fputcsv ($fp, $array, $deliminator=",") { $line = ""; foreach($array as $val) { # remove any windows new lines, # as they interfere with the parsing at the other end $val = str_replace("\r\n", "\n", $val); # if a deliminator char, a double quote char or a newline # are in the field, add quotes if(ereg("[$deliminator\"\n\r]", $val)) { $val = '"'.str_replace('"', '""', $val).'"'; }#end if $line .= $val.$deliminator; }#end foreach # strip the last deliminator $line = substr($line, 0, (strlen($deliminator) * -1)); # add the newline $line .= "\n"; # we don't care if the file pointer is invalid, # let fputs take care of it return fputs($fp, $line); }#end fputcsv() ?> http://php.net/manual/en/function.fgetcsv.php

« previous php.notes (#155112) next »