Creating CSV with PHP

有些话、适合烂在心里 提交于 2020-01-06 06:12:23

问题


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?


回答1:


Use the built in CSV functionality!

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

Reference

  • fputcsv
  • fgetcsv



回答2:


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);


来源:https://stackoverflow.com/questions/14914957/creating-csv-with-php

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!