Avoid default quotes from csv file when using fputcsv

Justin John picture Justin John · Jul 17, 2012 · Viewed 34.7k times · Source

Avoid default quotes from csv using fputcsv

fputcsv($fp, $array, ',', '"'); // OR fputcsv($fp, $array);

In test.csv

testname,045645765789,"""04.07.2012 12:10:52"""

How to avoid above quotes here?

Like below

testname,045645765789,04.07.2012 12:10:52

Answer

John C picture John C · Jul 17, 2012

Two double-quotes are used to escape double-quotes, so it looks like your date/time is already quoted. If you just want to get a correctly quoted CSV, you could try removing any existing double-quotes (this might be a bit brute force):

$array = array('testname',045645765789,'"04.07.2012 12:10:52"');
$array = str_replace('"', '', $array);

fputcsv($fp, $array);

// Output: testname,79323055,"04.07.2012 12:10:52"

The fputcsv wants to put something around a string with a space in it, so if you want no quotes at all you'll either need to work around or make your own function to do what you want. There are lots of good solutions under this question (edit: this was a different link). Alternately there are a number of other solutions in the comments of the PHP manual.

Based on the first link, you could do:

$array = array('testname',045645765789,'"04.07.2012 12:10:52"');
$array = str_replace('"', '', $array);

fputs($fp, implode(',', $array)."\n");

// Output: testname,79323055,04.07.2012 12:10:52