how to escape the delimiter from the column content when export csv

流过昼夜 提交于 2020-01-30 08:40:50

问题


Im up to export the CSV file, delimiter is a "," comma but im there is a problem if column content had comma , it will break the csv out put when looking on libre office calc.

if any body can help me how to solve this

here im upto now

//$filename = $row['fileName'].'-ConsignmentInfo.csv';
$filename="test.csv";
$delim = ',';
$columns = array('0Product_Number', 'Product_Name', 'Alternative_Title');
echo implode($delim,$columns )."\n";           

$ptr1 = DD_Db::fetch("SELECT p.pNum,p.pName,a.varcharValue FROM ds_products p   left join productAttribute a on a.id=p.pID where a.attributeId= (select id FROM attribute where attributeName='alternateTitle') ");

 foreach ($ptr1 as $row) {
      $line = array("\"{$row['pNum']}\"","\"{$row['pName']}\"","\"{$row['varcharValue']}\"");
      echo implode($delim,$line)."\n";
 }

header('Content-Type: text/csv');
header("Cache-Control: no-cache, must-revalidate"); // HTTP/1.1
header('Content-Disposition: attachment; filename='.$filename);
header('Pragma: cache');
header("Expires: Sat, 26 Jul 1997 05:00:00 GMT"); // Date in the past
exit;

回答1:


Just use fputcsv it takes care of escaping and producing correct csv data.

<?php

$list = array (
    array('aaa', 'bbb', 'ccc', 'dddd'),
    array('123', '456', '789'),
    array('"aaa"', '"bbb"')
);

$fp = fopen('file.csv', 'w');

foreach ($list as $fields) {
    fputcsv($fp, $fields);
}

fclose($fp);
?>

Output:

aaa,bbb,ccc,dddd
123,456,789
"""aaa""","""bbb"""

Edit

You can always use a combination of tmpfile to open a file that will be automatically deleted at the end of the request, write to it and then after the report is created output its content with fread. You have to use fread since tmpfile return a resource, otherwise you can use tempnam + file_get_contents but in that case you have to open the file and to cleanup after read it by yourself.




回答2:


The usual way is to wrap the piece of data with a pair of " and use "" to represent a double quote character in the data.

foo,bar,"sometimes you get data containing a "","" character","23,000"



回答3:


put in quotes the value.

http://pt.wikipedia.org/wiki/Comma-separated_values




回答4:


You can do it from a query using SELECT .. INTO OUTFILE e.g.

SELECT p.pNum, p.pName, a.varcharValue
FROM ds_products p   
LEFT JOIN productAttribute a ON a.id=p.pID 
WHERE a.attributeId = (select id FROM attribute where attributeName='alternateTitle')
INTO OUTFILE '/path/on/server'

If you want to add a header row:

SELECT 'A', 'B', 'C'
UNION
SELECT p.pNum, p.pName, a.varcharValue
FROM ds_products p   
LEFT JOIN productAttribute a ON a.id=p.pID 
WHERE a.attributeId = (select id FROM attribute where attributeName='alternateTitle')
INTO OUTFILE '/path/on/server'


来源:https://stackoverflow.com/questions/10226803/how-to-escape-the-delimiter-from-the-column-content-when-export-csv

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