note 14788 deleted from function.fgetcsv by sobak
| From: | sobak@php.net | Date: | Fri, 25 Nov 2016 06:36:54 +0000 |
| Subject: | note 14788 deleted from function.fgetcsv by sobak | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-207663@lists.php.net to get a copy of this message | ||
Note Submitter: blair at squiz . net
----
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.]