note 113326 added to function.fputcsv
| From: | R dot Mansveld at Spider-IT dot de | Date: | Fri, 27 Sep 2013 13:26:37 +0000 |
| Subject: | note 113326 added to function.fputcsv | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-196394@lists.php.net to get a copy of this message | ||
Inspired by boonerunner's function, I wrote a smaller, faster, and more flexible one, which
also uses less memory.
I also renamed it to avoid collision or overwriting the PHP function, and gave the 3rd and 4th
parameter default values like fputcsv() uses.
This function puts all text values in $enclosure's while doubling the $enclosure in the value,
and leaves numeric values as they are.
But if the $delimiter exists in the numeric value, this value will also be put in $enclosure's
(may happen if you use a dot as the $delimiter).
function fwritecsv($handle, $fields, $delimiter = ',', $enclosure = '"') {
# Check if $fields is an array
if (!is_array($fields)) {
return false;
}
# Walk through the data array
for ($i = 0, $n = count($fields); $i < $n; $i ++) {
# Only 'correct' non-numeric values
if (!is_numeric($fields[$i])) {
# Duplicate in-value $enclusure's and put the value in $enclosure's
$fields[$i] = $enclosure . str_replace($enclosure, $enclosure . $enclosure, $fields[$i])
. $enclosure;
}
# If $delimiter is a dot (.), also correct numeric values
if (($delimiter == '.') && (is_numeric($fields[$i]))) {
# Put the value in $enclosure's
$fields[$i] = $enclosure . $fields[$i] . $enclosure;
}
}
# Combine the data array with $delimiter and write it to the file
$line = implode($delimiter, $fields) . "\n";
fwrite($handle, $line);
# Return the length of the written data
return strlen($line);
}
----
Server IP: 87.106.1.137
Probable Submitter: 77.20.3.25
----
Manual Page -- http://php.net/manual/en/function.fputcsv.php
Edit -- https://master.php.net/note/edit/113326
Del: integrated -- https://master.php.net/note/delete/113326/integrated
Del: useless -- https://master.php.net/note/delete/113326/useless
Del: bad code -- https://master.php.net/note/delete/113326/bad+code
Del: spam -- https://master.php.net/note/delete/113326/spam
Del: non-english -- https://master.php.net/note/delete/113326/non-english
Del: in docs -- https://master.php.net/note/delete/113326/in+docs
Del: other reasons-- https://master.php.net/note/delete/113326
Reject -- https://master.php.net/note/reject/113326
Search -- https://master.php.net/manage/user-notes.php