Spiga

How to save data as a CSV file using PHP

There are multiple instances when you need to store the data as a file instead of outputting it in the browser. One common example is to store the data in a CSV (Comma Separated Values) file. You can output a file saving dialogue sending appropriate headers to the browser. Below is the example written in PHP. The code is commented so I hope there will be no difficulty in understanding.

01.
02.
03.// save the CSV data in a variable
04.$csvData = "name,email\n";
05.$csvData.= "waseem,waseem@waseem.com\n";
06.$csvData.= "ikram,ikram@ikram.com";
07.
08.// filename to save data
09.$filename = "sample.csv";
10.
11.// open file in write mode
12.$fh = fopen($filename, "w");
13.
14.// write data to the file
15.fwrite($fh, $csvData);
16.
17.// close the file
18.fclose($fh);
19.
20.// send headers to output the CSV data as a file
21.header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
22.header("Content-Length: " . strlen($csvData));
23.header("Content-type: text/x-csv");
24.header("Content-Disposition: attachment; filename=$filename");
25.echo $csvData;
26.
27.?>

0 comments:

ShareThis