Question

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):

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:

554,702180,25.00,6FYAK0,9090909090909090

What I need is this:

"554","702180","25.00","6FYAK0","9090909090909090"

Can someone jump start my brain?

Was it helpful?

Solution

I would use substitute function for fputscsv:

function my_fputcsv($handle, $fieldsarray, $delimiter = ",", $enclosure ='"'){
    $glue = $enclosure . $delimiter . $enclosure;
    return fwrite($handle, $enclosure . implode($glue,$fieldsarray) . $enclosure);
}

OTHER TIPS

HAve a look at the fputscsv command help on the PHP site: http://php.net/manual/en/function.fputcsv.php

The fourth parameter specifies an enclosure character. Is this what you are looking for? From what I understand, though, a CSV put will only include the quotes if the field requires it because of either delimeter characters or enclosure characters included in the field itself.

This is a quick fix, but it works.

$value = '554,702180,25.00,6FYAK0,9090909090909090';

$new_value = '"' . implode('","', explode(',', $value)) . '"';

echo $new_value;

Seems simple enough:

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

IF you want to write it without using fputscsv then you could use a function similar to this to generate a line to write to a file:

function csvify ($array)
{
   $temp = "";
   $counter = 0;
   foreach ($array as $element)
   {
      if ($counter > 0)
         $temp = $temp . ",";
      $counter ++;
      $temp = $temp . "\"$element\"";
   }
   return $temp;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top