PHPverse 2025

Voting

: seven plus zero?
(Example: nine)

The Note You're Voting On

R dot Mansveld at Spider-IT dot de
11 years ago
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);
}

<< Back to user notes page

To Top