Voting

: three minus one?
(Example: nine)

The Note You're Voting On

jon+dontspamme at phpsitesolutions dot com
16 years ago
I found that the fputcsv examples for PHP 4 missed one thing, that was proper handling of the $enclosure value when it is a quote (if a quote is passed in a field, and it is delimited by a slash, it will be improperly handled by the functions submitted here).

My modified function was built using the actual PHP5 source for fputcsv, with the addition of properly reacting to the existence of a delimited quote in the field being processed.

<?php
if (!function_exists('fputcsv')) {
function
fputcsv(&$handle, $fields = array(), $delimiter = ',', $enclosure = '"') {

// Sanity Check
if (!is_resource($handle)) {
trigger_error('fputcsv() expects parameter 1 to be resource, ' .
gettype($handle) . ' given', E_USER_WARNING);
return
false;
}

if (
$delimiter!=NULL) {
if(
strlen($delimiter) < 1 ) {
trigger_error('delimiter must be a character', E_USER_WARNING);
return
false;
}elseif(
strlen($delimiter) > 1 ) {
trigger_error('delimiter must be a single character', E_USER_NOTICE);
}

/* use first character from string */
$delimiter = $delimiter[0];
}

if(
$enclosure!=NULL ) {
if(
strlen($enclosure) < 1 ) {
trigger_error('enclosure must be a character', E_USER_WARNING);
return
false;
}elseif(
strlen($enclosure) > 1 ) {
trigger_error('enclosure must be a single character', E_USER_NOTICE);
}

/* use first character from string */
$enclosure = $enclosure[0];
}

$i = 0;
$csvline = '';
$escape_char = '\\';
$field_cnt = count($fields);
$enc_is_quote = in_array($enclosure, array('"',"'"));
reset($fields);

foreach(
$fields AS $field ) {

/* enclose a field that contains a delimiter, an enclosure character, or a newline */
if( is_string($field) && (
strpos($field, $delimiter)!==false ||
strpos($field, $enclosure)!==false ||
strpos($field, $escape_char)!==false ||
strpos($field, "\n")!==false ||
strpos($field, "\r")!==false ||
strpos($field, "\t")!==false ||
strpos($field, ' ')!==false ) ) {

$field_len = strlen($field);
$escaped = 0;

$csvline .= $enclosure;
for(
$ch = 0; $ch < $field_len; $ch++ ) {
if(
$field[$ch] == $escape_char && $field[$ch+1] == $enclosure && $enc_is_quote ) {
continue;
}elseif(
$field[$ch] == $escape_char ) {
$escaped = 1;
}elseif( !
$escaped && $field[$ch] == $enclosure ) {
$csvline .= $enclosure;
}else{
$escaped = 0;
}
$csvline .= $field[$ch];
}
$csvline .= $enclosure;
} else {
$csvline .= $field;
}

if(
$i++ != $field_cnt ) {
$csvline .= $delimiter;
}
}

$csvline .= "\n";

return
fwrite($handle, $csvline);
}
}
?>

<< Back to user notes page

To Top