Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wrap CSV values generated by PHP fputcsv() with " "

Tags:

php

csv

So, my code generates a CSV file using PHP's built-in fputcsv function.

For the delimiter, I use ',' (a comma).
For the enclosure, I use '"' (a double-quote).

However, when I try something like

fputcsv($file,array('a','b',"long string, with commas",NULL,''),',','"');

it outputs

a,b,"long string, with commas",,

but I would like it to output

"a","b","long string, with commas","",""

Is there an easy way to deal with this, or would I have to write a replacement for fputcsv?

like image 343
Austin Hyde Avatar asked Sep 28 '10 22:09

Austin Hyde


People also ask

How does PHP Fputcsv work?

fputcsv() function in PHP The fputcsv() function formats a line as CSV and writes it to an open file. The function returns the length of the written string.

How do I read a csv file in column wise in PHP?

You can open the file using fopen() as usual, get each line by using fgets() and then simply explode it on each comma like this: <? php $handle = @fopen("/tmp/inputfile. txt", "r"); if ($handle) { while (($buffer = fgets($handle)) !==

How do I add a new row to an existing CSV file in PHP?

php $list = array ( 'Peter,Griffin,Oslo,Norway', 'Glenn,Quagmire,Oslo,Norway', ); $file = fopen('contacts. csv','a'); // 'a' for append to file - created if doesn't exit foreach ($list as $line) { fputcsv($file,explode(',',$line)); } fclose($file); ?>


Video Answer


1 Answers

This is not usually a problem for CSV files.

fputcsv puts quotes around the value if it would be ambiguous. For example,

a,b,"long string, with commas",,

is not ambiguous, but,

a,b,long string, with commas,,

is, and will in most (read: all) cases be interpreted by the CSV reader as having more than 5 fields.

CSV parsers will accept string literals even without quotes around them.

If you want quotes around the values anyway, the following snippet would do that. It doesn't escape quotes inside the string - that exercise is left to the reader:

$row = '"' . implode('", "', $rowitems) . '"';

You would want to put this in a loop for all your rows.

like image 72
Thomas O Avatar answered Nov 09 '22 13:11

Thomas O