2

When I want to put data in a CSV/Excel file it will automatically put all data in one column. This isn't very clear to read and I would like to have a single column for each data. Here is my code:

<?php
$data = array(
  'aaa,bbb,ccc,dddd',
  '123,456,789',
  '"aaa","bbb"'
);
$fp = fopen('test.csv', 'w');
foreach ( $data as $line ) {
  $val = explode(",", $line);
  fputcsv($fp, $val);
}
fclose($fp);
?>

and this is what it is showing inside the CSV/excel file:

How it is now:

How it is now

And here is how it should be:

How it should be

3
  • If you want to create a proper Excel file with the format you want, try out PHPSpreadsheet instead. What you're doing now is simply creating a CSV-file which you then open in Excel. At that point, it's up to Excel to parse the file and won't have anything to do with your code. Commented Dec 9, 2019 at 10:30
  • 1
    Show us the contents of the CSV file, open it in a notebook. You probably choose the wrong delimiter when you open the CSV file in Excel (you choose ";" instead of ","). Commented Dec 9, 2019 at 10:30
  • you need to specify coma delimiter in Excel during import Commented Dec 9, 2019 at 10:31

2 Answers 2

2

Try it like this:

<?php
$data = array(
  'aaa,bbb,ccc,dddd',
  '123,456,789',
  '"aaa","bbb"'
);
$fp = fopen('test.csv', 'w');
foreach ( $data as $line ) {
  $val = explode(",", $line);
  fputcsv($fp, $val, ";");
}
fclose($fp);
?>
Sign up to request clarification or add additional context in comments.

Comments

0

Seems that fputcsv use semicolon as default delimiter. You can pass the delimiter you want as third parameter to fputcsv.

$data = array(
    'aaa,bbb,ccc,dddd',
    '123,456,789',
    '"aaa","bbb"'
);
$fp = fopen('test.csv', 'w');
foreach ( $data as $line ) {
    $val = explode(",", $line);
    fputcsv($fp, $val, ',');
}
fclose($fp);

Comments

Your Answer

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