How to quote all values in fputcsv?
Posted: Mon Nov 01, 2010 4:45 pm
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):
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:
What I need is this:
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:
but that returns this:
Is there really no way 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);Code: Select all
554,702180,25.00,6FYAK0,9090909090909090Code: Select all
"554","702180","25.00","6FYAK0","9090909090909090"I've tried this:
Code: Select all
$newrow[$key] = '"' . preg_replace("(\r\n|\n|\r|\t)", "", $val) . '"';Code: Select all
"""554""","""702180""","""25.00""","""6FYAK0""","""9090909090909090"""