An improved version of the function from php.net
function download_csv_results($results, $name = NULL)
{
if( ! $name)
{
$name = md5(uniqid() . microtime(TRUE) . mt_rand()). '.csv';
}
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename='. $name);
header('Pragma: no-cache');
header("Expires: 0");
$outstream = fopen("php://output", "w");
fputcsv($outstream, array_keys($results[0])); //This will include column headers
foreach($results as $result)
{
fputcsv($outstream, $result);
}
fclose($outstream);
}
require_once("yourdatabaseconnection.php"); //Include your database connection here
$sql = mysql_query("SELECT * FROM your_table'") or die(mysql_error());
if(mysql_num_rows($sql) > 0)
{
$results = array();
while($rows = mysql_fetch_assoc($sql)){
$results[] = $rows;
}
//call your function here
download_csv_results($results, 'your_file_name_here.csv'); }