Lain
Lain

Reputation: 2216

Array to csv download in PHP

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?

Upvotes: 1

Views: 2977

Answers (2)

Nghi Ho
Nghi Ho

Reputation: 463

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

Upvotes: 1

sietse85
sietse85

Reputation: 1506

You have to add a newline

echo $line . "\n";

Even better

echo $line . PHP_EOL; //constant for correct line-ending depending on OS.

Upvotes: 3

Related Questions