Reputation: 4349
i'm using fputcsv
and its only putting input text type values into quotes. Is there a way to override this and either force all to have quotes or remove them all together? I tried fputcsv($fp, $data, ',', '"');
but that didn't work
$data = array_values($_POST);
if( $fp = fopen('data.csv', 'a+') ){
fputcsv($fp, $data);
}
fclose($fp);
csv data example: "user","city",yes,no,10001
Upvotes: 0
Views: 1090
Reputation: 1169
You can force each entry to be quoted by appending a space, then remove that space using a stream filter before it gets written to the .csv
/* Function to append a space to each element in the array */
function addSpace(&$var, $key){ $var .= ' '; }
/* Filter class to remove the space previously appended */
class space_filter extends php_user_filter {
function filter($in, $out, &$consumed, $closing)
{
while ($bucket = stream_bucket_make_writeable($in)) {
$bucket->data = str_replace(' "', '"', $bucket->data);
$consumed += $bucket->datalen;
stream_bucket_append($out, $bucket);
}
return PSFS_PASS_ON;
}
}
/* Register filter */
stream_filter_register("filterspace", "space_filter");
$arr = array("user","city","yes","no","10001"); // your array
/* use addSpace on each element in the array */
array_walk($arr, "addSpace");
if( $fp = fopen('data.csv', 'a+') ){
stream_filter_append($fp, "filterspace"); // Remove space
fputcsv($fp, $arr);
}
fclose($fp);
Results in: "user","city","yes","no","10001"
I just wrote this out of curiosity, you probably shouldn't use this for anything important.
Upvotes: 1