Utility function to output a mysql query to csv with the option to write to file or send back to the browser as a csv attachment.
<?php
function query_to_csv($db_conn, $query, $filename, $attachment = false, $headers = true) {
if($attachment) {
header( 'Content-Type: text/csv' );
header( 'Content-Disposition: attachment;filename='.$filename);
$fp = fopen('php://output', 'w');
} else {
$fp = fopen($filename, 'w');
}
$result = mysql_query($query, $db_conn) or die( mysql_error( $db_conn ) );
if($headers) {
$row = mysql_fetch_assoc($result);
if($row) {
fputcsv($fp, array_keys($row));
mysql_data_seek($result, 0);
}
}
while($row = mysql_fetch_assoc($result)) {
fputcsv($fp, $row);
}
fclose($fp);
}
$sql = "SELECT * FROM table";
query_to_csv($db_conn, $sql, "test.csv", true);
query_to_csv($db_conn, $sql, "test.csv", false);
?>