Skip to content

Instantly share code, notes, and snippets.

@snowbob
Created October 19, 2016 07:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save snowbob/29370beb86110c40fea2b1b3d9b88830 to your computer and use it in GitHub Desktop.
Save snowbob/29370beb86110c40fea2b1b3d9b88830 to your computer and use it in GitHub Desktop.
// output headers so that the file is downloaded rather than displayed
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename=data.csv');
// create a file pointer connected to the output stream
$output = fopen('php://output', 'w');
// output the column headings
fputcsv($output, array('Column 1', 'Column 2', 'Column 3'));
// fetch the data
mysql_connect('localhost', 'username', 'password');
mysql_select_db('database');
$rows = mysql_query('SELECT field1,field2,field3 FROM table');
// loop over the rows, outputting them
while ($row = mysql_fetch_assoc($rows)) fputcsv($output, $row);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment