Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Avoid default quotes from csv file when using fputcsv

Tags:

php

fputcsv

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
like image 206
Justin John Avatar asked Jul 17 '12 06:07

Justin John


1 Answers

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 
like image 184
John C Avatar answered Oct 14 '22 02:10

John C