y2p
y2p

Reputation: 4931

Download PHP array as a file

I have an array with 3 attributes. I want to create a downloadable link for a file which has the array in a tab-delimited format.

ATTR1     ATTR2     ATTR3
23.7      45.89     1.09
....      .....     ....
....      .....     ....
....      .....     ....

Upvotes: 1

Views: 2883

Answers (2)

Gleb M Borisov
Gleb M Borisov

Reputation: 607

You should output content like ususal and set addition header (before you output any content).

<?php
header("Content-Disposition", 'attachment, filename="NAMEOFFILE.tsv"')

// output content in tab delimited format below
?>

And then point your link to this script. When user hit it - download window appear (or file will be opened in application, depends on browser settings).

Upvotes: 2

Mark Baker
Mark Baker

Reputation: 212412

$headings = array('ATTR1','ATTR2','ATTR3');

$fp = fopen('file.csv', 'w');

fputcsv($fp,$headings,"\t");
foreach($array as $row) {
   fputcsv($fp,$row,"\t");
}

fclose($fp);

Upvotes: 5

Related Questions