How to Write a CSV Directly to PHP://Output I/O Buffer With fputcsv()


Came across this gem half-way down the function page for fputcsv() on php.net

// Send headers for file
header( 'Content-Type: text/csv' );
header( 'Content-Disposition: attachment;filename='.$filename);
// open buffer to write file to browser
$fp = fopen('php://output', 'w'); 

// Table Headings row
fputcsv($fp, array_keys($row));

// Write rows to buffer 
while($row = mysql_fetch_assoc($result)) {
    fputcsv($fp, $row);
}

Use an associative array for this so your keys will be the csv headers.

Enjoy!