Thursday, October 27, 2011

PHP to CSV simplest way

Many times we need to download a CSV file from database using PHP. Here is a simple method..

Step 1: Prepare Query.

$query="SELECT * FROM TABLEA";

Step 2 : Fetch data from database using above query.
$result= $Dbase->execute($query);

Remember in above i using my own function coded by me. but you can use mysql_fetch_assoc or mysql_fetch_array for the data fetch.

Now prepare the header to put a CSV for download -

header("Content-type: text/csv");
header("Content-Disposition: attachment; filename=myfile.csv");
header("Pragma: no-cache");
header("Expires: 0");


myfile is semicolon (; seperated values with a new line for end of file) csv file. I am preparing it as follows

Now Write in this file using simple ECHO - (Header Column)
echo "COLUMN-A; COLUMN-B; COLUMN-C; \n";

Now the values (Data values)
for( $i=0; $i<=Count($result)-1; $i++ ) { echo $result[$i][0].";".$result[$i][1].";".$result[$i][2]."; \n"; }

at the end you have a CSV ready (simple and clear).

No comments:

Post a Comment