Skip to content

Instantly share code, notes, and snippets.

@benbuckman
Created April 14, 2011 20:39
Show Gist options
  • Star 12 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save benbuckman/920477 to your computer and use it in GitHub Desktop.
Save benbuckman/920477 to your computer and use it in GitHub Desktop.
<?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
@sakawsar
Copy link

Thank you. It worked fine.

@Mainul163
Copy link

Thank You .

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment