Make CSV File from Database

Like this blog? Consider exploring one of our sponsored banner ads...

This is the easiest way to make a CSV file from a database query and output it to the user for download. This simple code uses the PHP5 fputcsv function to correctly format an array of values into a line in a csv file. It does not use the physical file so you do not need any write permissions where you use this code, as it uses the memory buffer instead.

$output = fopen('php://temp/maxmemory:'. (5*1024*1024), 'r+');
 
$columns = array('Field1','Field2','Field3','Field4','Field5');
 
fputcsv($output, $columns);
 
$query = mysql_query("SELECT * FROM `table`");
 
while ($data = mysql_fetch_assoc($query)){
 
	fputcsv($output, $data);
}
 
rewind($output);
 
$export = stream_get_contents($output);
 
fclose($output);
 
header('Content-type: application/octet-stream');
 
header('Content-Disposition: attachment; filename="export.csv"');
 
echo $export;

About this entry