简体   繁体   中英

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

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;

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.

通常的方法是用一对"包装数据,并使用""表示数据中的双引号字符。

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

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

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'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM