Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
<?php
// force download of CSV
// simulate file handle w/ php://output, direct to output (from http://www.php.net/manual/en/function.fputcsv.php#72428)
// (could alternately write to memory handle & read from stream, this seems more direct)
// headers from http://us3.php.net/manual/en/function.readfile.php
header('Content-Description: File Transfer');
header('Content-Type: application/csv');
header("Content-Disposition: attachment; filename=FILENAME.csv");
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
$handle = fopen('php://output', 'w');
ob_clean(); // clean slate
// [given some database query object $result]...
while ($row = db_fetch_array($result)) {
// parse the data...
fputcsv($handle, $row); // direct to buffered output
}
ob_flush(); // dump buffer
fclose($handle);
die();
// client should see download prompt and page remains where it was
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment