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
?
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.
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)) !==
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); ?>
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With