Podrias utilizar una rutina parecida a esta:
Código PHP:
<?php
$selTotal = "SELECT * FROM api_orders_history";
$selTotalExec = mysql_query($selTotal, $catalogoSTD) or die( mysql_error() );
$elCSV = 'No. PEDIDO, CODIGO CLIENTE, CODIGO PRODUCTO, CANTIDAD';
$elCSV .= "\r\n";
$csvName = "archivos/pedidos". date('Ymd') .".csv";
$fileHandle = fopen($csvName, 'w') or die('Can\'t create .csv file, try again later.');
while( $elTotal = mysql_fetch_assoc($selTotalExec) ){
// echo($elTotal['company_code']);exit;
$elCSV .= $elTotal['order_code'].",".$elTotal['company_code'].",".$elTotal['product_code'].",".$elTotal['product_quantity']." \n ";
// create and write file
fwrite($fileHandle, $elCSV);
//echo($elTotal['id']."<br />");
}
fclose($fileHandle);
//}
// push file to browser
header('Content-Type: application/x-octet-stream');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Last-Modified: '.date('D, d M Y H:i:s'));
header('Content-Disposition: attachment; filename="Reporte_de_pedidos'. date('Ymd') .'.csv"');
header("Content-Length: ".filesize($csvName));
// echo $csvContent;
// delete file
// unlink($csvName);
echo($elCSV);
?>
http://php.net/fopen
un saludo.