1

I am trying to turn my array in PHP into a csv to download.

Currently the array looks something like this

Array[0] = "Name,age,ID"
Array[1] = "Alex,26,1"
Array[2] = "Ryan,12,2"
Array[3] = "Steph,56,7"

etc

I was unsure how to make this download as a csv, where each array position is its own line is csv obviously.

I set the headers to the following :

header("Content-type: text/csv");
header("Content-Disposition: attachment; filename=file.csv");

then I tried to echo each element of the array, hoping this would work. as follows:

header("Content-type: text/csv");
 header("Content-Disposition: attachment; filename=file.csv");
foreach ($lines as &$line) {
   echo $line;
}

Where $lines was my array.

However it did all one line in the csv. Is there a way I can turn this array to print properly in csv?

3
  • @PatrickQ done, was just a basic echo, didn't think it was needed. Commented Oct 11, 2018 at 17:42
  • echo "$line\n"; Commented Oct 11, 2018 at 17:43
  • echo doesn't automatically add newlines at the end of your content. You have to do that explicitly. Commented Oct 11, 2018 at 17:43

2 Answers 2

3

You have to add a newline

echo $line . "\n";

Even better

echo $line . PHP_EOL; //constant for correct line-ending depending on OS.
Sign up to request clarification or add additional context in comments.

2 Comments

Use PHP_EOL for cross-platform newline: echo $line, PHP_EOL;
dear god I'm dumb. Think after coding in PHP for almost 2 years I would have caught that. I'll accept the answer when it lets me.
1

One of solution is fputcsv function.

header("Content-type: text/csv");
header("Content-Disposition: attachment; filename=file.csv");
$output = fopen('php://output', 'w');
foreach ($lines as $line) {
    $row = explode(',', $line);
    fputcsv($output, $row);
}
fclose($output);

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.