stefgosselin stefgosselin - 4 months ago 11x
PHP Question

enclosure parameter in fputcsv not behaving as expected

This I believe has a simple explanation, I just cannot see it. I want to generate a pretty simple csv delimetered file with double quotes around field values.

As per the manual page on fputcsv(), I try to pass on the delimiter and enclosure argument explicitly to have double-quoted field values required for data import in third-party application as in function call below:

// relevant line of codes ...
while($row = mysql_fetch_array($result)){

$name_pieces = "";
$name_pieces = explode(" ", $row['name']);

$numberOfPieces = count($name_pieces);

$lastNameIndex = $numberOfPieces - 1;

$lastname = $name_pieces[$lastNameIndex];
$firstname = $name_pieces[0];

} // Line array becomes the first, second, third fields in resulting .csv output.

$line = array( $row['username'],
$row['description'] );

$data[] = $line;

foreach($data as $dataLine){
if(fputcsv($fh, $dataLine, ',', '"') === false){
die("Unable to write to csv file.");

Following is a sample of the script's .csv output, notice that only second and last fields are quoted.

AG,"Alan Gaulois",Alan,Gaulois,"(AG) Alan Gaulois"
COMMIS,commis,commis,commis,"(COMMIS) commis"
DU,"Denis Fargo",Denis,Fargo,"(DF) Denis Fargo"

Anyone have an idea why the fields are not all quoted? I could well have missed something on doc page, any insight appreciated!

Ben Ben

To my knowledge, yes, delimiters are only needed if there are spaces, if you need something else, consider using array_map.

Something like:

function surroundWithQuotes ($input)
    $input = str_replace('"', '""', $input); //escaping in csv files is done by doing the same quote twice, odd
    return '"' . $input . '"';

foreach($data as $dataLine){
    if(fputcsv($fh, array_map("surroundWithQuotes" $dataLine),$dataLine, ',', '') === false){
      die("Unable to write to csv file.");