0

In csv file i need a comma in column value.

Here is the mysql query:

$q_pack = "select p.filename, p.version, dt.name as external,p.internal
          from cert c 
            join packages p on c.package_id=p.id 
            left join documents dt on p.id=dt.package_id 
            left join documents doc on doc.id=d.document_id 
          where c.certificate_id=100";

$res_pack = db_query($q_pack);
if ($res_pack){
$fp = fopen('sample.csv', 'w');
$title = "filename, version, external,internal";
fwrite($fp, $title);
while ($pack_row = db_fetch_object($res_pack)){
fwrite($fp, "\n");
foreach ( $pack_row as $line ) {
$val = $line.',';
fwrite($fp, $val);}}
fclose($fp);}

Here column name as "external" and the value is joe,bob. In mysql table the value of external return as joe,bob, but in csv file it displayed as joe is in one column and bob is in another column.

Please refer the screenshot for CSV file. Csv file

10
  • need to escape the column headers Commented May 4, 2017 at 13:55
  • @clearshot66 can you please explain it briefly Commented May 4, 2017 at 13:56
  • fputcsv($fp, array('Column 1', 'Column 2', 'Column 3', 'Column 4', 'Column 5')); wouldn't this work? Commented May 4, 2017 at 13:57
  • You should enclose it. The default enclosure is double quotes. In this way you can parse it back using str_getcsv php.net/manual/en/function.str-getcsv.php And see related question: stackoverflow.com/questions/6536826/dealing-with-commas-in-csv Commented May 4, 2017 at 13:59
  • @PrashanthBenny I'm using the mysql query, then where should i mention fputcsv Commented May 4, 2017 at 14:00

1 Answer 1

2

You should use fputcsv() it will automatically enclosure your fields with commas in double quotes

$res_pack = db_query($q_pack);
$fp = fopen('sample.csv', 'w');
fputcsv($fp, ['filename', 'version', 'external', 'internal']);
while ($pack_row = db_fetch_array($res_pack)) {
    fputcsv($fp, $pack_row);
}
fclose($fp);

So in this case, sample row:

array(
    'filename' => 'file',
    'version' => 10
    'external' => 'foo,bar'
    'internal' => 'baz'
);

will be encoded as follows file,10,"foo,bar",baz

Read more: http://php.net/manual/en/function.fputcsv.php

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.