PHP – MySQL to CSV

The given PHP example takes a mysql query and turns it into a csv file that downloads automatically.

Code Example:
<?php
header("Content-type: text/csv");
header("Content-Disposition: attachment; filename=export.csv");
header("Pragma: no-cache");
header("Expires: 0");
$qry=mysql_query('select * from product');
while($r=mysql_fetch_array($qry)){
	foreach($r as $key => $val){
		if(is_numeric($key)){
			echo '"'.str_replace('"', '""', $val).'",';
		}
	}
	echo "\n";
}
?>

Post to Twitter Post to Digg Post to Facebook Post to Google Buzz Send Gmail

Leave a Comment

Your email address will not be published. Required fields are marked *