Forked from benbuckman/php: output to downloaded csv.php
Created
August 8, 2021 14:04
-
-
Save longnz/90d55aac3ec1c5d40181441b4ffc17d1 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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