Page 1 of 1

How to quote all values in fputcsv?

Posted: Mon Nov 01, 2010 4:45 pm
by esthermstrom
I have a piece of php code that reads values from a database resultset, shoves them into an array, and writes them to a CSV file. I need to force each value to be surrounded by double quotes when it goes into the CSV file, and can't for the life of me remember how to do this.

Here's the loop that writes to the file (this is actually contained in another loop to go through each row; this loop I'm showing goes through the columns in the currently-selected row):

Code: Select all

foreach ($row as $key => $val){
    $newrow[$key] = preg_replace("(\r\n|\n|\r|\t)", "", $val);
}

fputcsv($fp, $newrow);
What I need is for the value of $val to be enclosed in double quotes when it's written to the file. Right now, the results I get look like this:

Code: Select all

554,702180,25.00,6FYAK0,9090909090909090
What I need is this:

Code: Select all

"554","702180","25.00","6FYAK0","9090909090909090"
Can someone jump start my brain? I've already posted on stackoverflow, and basically all anyone could tell me was that fputcsv has a fourth parameter for string enclosure. The problem is, that only adds quotes for fields that are text-ish in the database. I have fields that are defined as dates, integers, etc., and all of them need to be quoted, because we're passing this data on to a legacy system that requires all import values to be in double quotes.

I've tried this:

Code: Select all

$newrow[$key] = '"' . preg_replace("(\r\n|\n|\r|\t)", "", $val) . '"';
but that returns this:

Code: Select all

"""554""","""702180""","""25.00""","""6FYAK0""","""9090909090909090"""
Is there really no way to do this?

Re: How to quote all values in fputcsv?

Posted: Tue Nov 02, 2010 5:43 am
by cpetercarter
Have you tried casting each value as a string before putting it into $newrow?

Like this:

Code: Select all

foreach ($row as $key => $val){
    $t = preg_replace("(\r\n|\n|\r|\t)", "", $val);
    $newrow[$key] = (string)$t;
}

fputcsv($fp, $newrow);

Re: How to quote all values in fputcsv?

Posted: Tue Nov 02, 2010 10:22 am
by AbraCadaver
Might work:

Code: Select all

fputcsv($fp, array_map('strval', $newrow), ',', '"');

Re: How to quote all values in fputcsv?

Posted: Tue Nov 02, 2010 10:43 am
by Weirdan
fputcsv does not let you force the quoting. You need to use something different, like Luke's php-csv-utils: http://code.google.com/p/php-csv-utils/