Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Output to CSV with ' " ' enclosures

Tags:

php

csv

I want to output a query to a csv file with " enclosures around all fields.

The following:

header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename='.$strFeederFileName.'');

$output = fopen('php://output', 'r+');
$fileheader = array( "FH", "READY TO PAY", "RTP060620134", "060620134RWKN", "");
fputcsv($output, $fileheader, ",", '"');

Outputs this:

FH,"READY TO PAY",RTP060620134,060620134RWKN

but I need it to be:

"FH","READY TO PAY","RTP060620134","060620134RWKN"

Any ideas why it's not adding enclosures to fields 1, 3 & 4?

like image 644
Dion Avatar asked Jun 06 '13 20:06

Dion


People also ask

What is enclosure in CSV?

Delimiter : a character used as a delimiter between values. The default is the comma: , . Enclosure Character : a character used to enclose the field value. By default, only the values that contain Delimiter will be enclosed. Enable Always enclose to enclose all values.


2 Answers

fputcsv is pretty smart at guessing which columns need to have brackets and don't in order to keep the CSV valid.

At the moment it's outputting valid CSV.

fputcsv doesn't provide an option to force enclosing in quotes, it'd probably be good to know why you need them to all be in quotes?

like image 197
rob_mccann Avatar answered Sep 22 '22 01:09

rob_mccann


Gumby's comment is correct - if it doesnt need to enclose in quotes, it wont. You could do something like set the enclosure to an empty string, and put them on yourself:

$fileheader = array( "FH", "READY TO PAY", "RTP060620134", "060620134RWKN", "");
for($i=0; $i<count($fileheader); $i++) 
{ 
    $fileheader[i] = '"' . $fileheader[$i] . '"'; 
}
fputcsv($output, $fileheader, ",", '');
like image 27
dave Avatar answered Sep 21 '22 01:09

dave