Skip to content

Instantly share code, notes, and snippets.

@rmontagud
Last active September 4, 2022 03:24
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rmontagud/1074382 to your computer and use it in GitHub Desktop.
Save rmontagud/1074382 to your computer and use it in GitHub Desktop.
Export a MySQL dataset to CSV using php://output stream and fputcsv
<?php
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment;filename="export.csv"');
header('Cache-Control: max-age=0');
// See: http://es2.php.net/manual/en/wrappers.php.php
$fpcsv = fopen('php://output', "a+");
// Put your SQL query here
$exportcsv_q = mysql_query($query);
if (@mysql_num_rows($exportcsv_q) > 0) {
$campos = mysql_num_fields($exportcsv_q);
while ($exportcsv_r = mysql_fetch_row($exportcsv_q)) {
fputcsv($fpcsv, $exportcsv_r);
}
}
exit;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment