1

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
  • 1
    What result do you expect to have? At this moment you have an array with one item which you write as a single line. Commented Jul 12, 2018 at 0:30
  • Hi, I just adjusted the question to show what I want. Thanks @zerkms Commented Jul 12, 2018 at 0:34

2 Answers 2

3

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);
Sign up to request clarification or add additional context in comments.

1 Comment

RenegadeRob: if you’re satisfied with this answer, you can mark it as the accepted answer to let the community know that your question has been answered and to give Erwin credit for it.
1

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

2 Comments

This would be good, but the actual $arraybuild is in a loop adding lines for the CSV. so I cant rename each variable in the loop because it will never be the same amount.
sure thing, variables here are just for example. @Erwin's answer may be more specific to what you're looking for

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.