Renegade Rob
Renegade Rob

Reputation: 403

PHP Building an array with variables

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?

Upvotes: 1

Views: 535

Answers (2)

Goma
Goma

Reputation: 1981

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);

Upvotes: 3

Maxim Mazurok
Maxim Mazurok

Reputation: 4128

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);

Upvotes: 1

Related Questions