1
votes

I want to build an array to create a CSV file using variables. The $arraybuild variable will gather lines from a search so will never be the same amount of rows.

$arraybuild = "'aaa,bbb,ccc,dddd',";
$arraybuild .= "'123,456,789',";
$arraybuild .= "'\"aaa\",\"bbb\"'";

$list = array
(
    $arraybuild
)
;

$file = fopen("contacts.csv","w");

foreach ($list as $line)
  {
  fputcsv($file,explode(',',$line));
  }

fclose($file);

The problem is the result does not separate the lines, it places them all in the same line.

I want to get

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

What I am getting is

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

All in separate columns

Can someone please assist?

2
What result do you expect to have? At this moment you have an array with one item which you write as a single line.zerkms
Hi, I just adjusted the question to show what I want. Thanks @zerkmsRenegade Rob

2 Answers

3
votes

Push each rows to an array instead of concatenating to a string, then loop and add to csv

$arraybuild[] = "'aaa,bbb,ccc,dddd',";
$arraybuild[] = "'123,456,789',";
$arraybuild[] = "'\"aaa\",\"bbb\"'";

$file = fopen("contacts.csv","w");

foreach ($arraybuild as $line) {
    fputcsv($file, explode(',', $line));
}

fclose($file);
1
votes

In your code, you are concatenating all values to one string, separated by ,. After that, you are creating one array with one element in it (that long string).

So, it's not a surprise, that you are getting all of them on the same line.

To separate lines, you should create separate arrays inside the $list array. Each included array will be on the new line.

Try this:

<?php

$arraybuild1 = "'aaa,bbb,ccc,dddd',";
$arraybuild2 = "'123,456,789',";
$arraybuild3 = "'\"aaa\",\"bbb\"'";

$list = array
(
    explode(',', $arraybuild1),
    explode(',', $arraybuild2),
    explode(',', $arraybuild3)
);

$file = fopen("contacts.csv", "w");

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

fclose($file);