Wally Kolcz
Wally Kolcz

Reputation: 1664

Creating CSV with PHP

I am attempting to create a dynamic csv file to export to a vendors site on my site. They want all values surrounded with double quotes. I am attempting to create the line then feed it to a fputcsv() but its coming out with a ton of double quotes when I view it in notepad2 and as 1 entry when viewing it in Excel. Here are my values:

$line = '"'.$row->petID.'","'.$row->customID.'","'.$row->petName.'","'.trim($row->breedName1).'","'.trim($row->breedName2).'","'.$df->setGender($row->gender).'","'.$df->setSize($row->size).'","'.$df->setAge($row->age).'","'.$description.'","'.$row->pType.'","'.$df->setStatus($row->status).'","","'.$row->isAltered.'","'.$ND.'","'.$NC.'","'.$NK.'","'.$df->isHousetrained($row->housebroken).'","'.$df->isDeclawed($row->declaw).'","'.$df->isSpecialNeeds($row->isSpecial).'","'.$df->isMix($row->breed2).'","'.$PhotoURL1.'","'.$PhotoURL2.'","'.$PhotoURL3.'"';

and it comes out like this using a text editor: """13651"","""",""jack"",""Chihuahua"",""Pomeranian"",""M"",""S"",""Baby"",""Jack and Jose were born to a cute 7lb Chihuahua/Pomeranian mix who was brought to the shelter as a stray. they will be weaned for their new home mid August.Although the father is unknown, pups will most likely remain small.Please visit our website at www.dogswithoutborders.org for an online adoption application for either Jack or Jose and to learn more about our adoption fairs."",""Dog"",""A"","""",""0"","""","""","""","""","""","""",""1"",""http://photos.petfinder.com/photos/US/CA/CA1087/20460152/CA1087.20460152-1-x.jpg"","""","""""

When I remove the manually added "(s) I get only one in the beginning and one on the end. Any ideas?

Upvotes: 0

Views: 7985

Answers (2)

Tucker
Tucker

Reputation: 7362

Instead of doing it yourself, you can use this PHP function:

fputcsv

The documentation is here: http://php.net/manual/en/function.fputcsv.php

as in the documentation, you can...

//put your data in an array like this:
$list = array (
    array('aaa', 'bbb', 'ccc', 'dddd'),
    array('123', '456', '789'),
    array('"aaa"', '"bbb"')
);
//open the output file for writing
$fp = fopen('file.csv', 'w');

//write to the csv file (comma separated, double quote enclosed)
foreach ($list as $fields) {
    fputcsv($fp, $fields,',','"');
}
//close the file
fclose($fp);

Upvotes: -1

John Conde
John Conde

Reputation: 219804

Use the built in CSV functionality!

<?php
    $fp = fopen('file.csv', 'w');
    fputcsv($fp, array('item1','items'));
    fclose($fp);
?>

Reference

Upvotes: 5

Related Questions