Skip to content

Instantly share code, notes, and snippets.

@EricYue2012
Created December 6, 2013 00:40
Show Gist options
  • Save EricYue2012/7816799 to your computer and use it in GitHub Desktop.
Save EricYue2012/7816799 to your computer and use it in GitHub Desktop.
PHP output excel file
http://stackoverflow.com/questions/8082523/export-records-in-excel-file
1. Do query in php to get the rows you want to output
2. You can use SELECT * FROM table WHERE id IN (1,2,...)
3. Use mysql_fetch_array() or mysql_fetch_assoc() to get the rows one at a time
4. Use fputcsv() to output them to a file ending in csv - this will properly escape your data
Excel will be able to read the file.
Override the defaults for fputcsv to use tabs for delimiters and Excel will have an even easier time reading the file. If you use commas (the default) you may need to pick commas as the delimiter on Excel import.
Here's a working example assuming you already have rows set up:
////////////////////////////////////////////////////////////////////////////////////////
$rows; // predefined
$filename = 'webdata_' . date('Ymd') . '.csv';
header("Content-Disposition: attachment; filename=\"$filename\"");
header("Content-Type: application/octet-stream");
// that indicates it is binary so the OS won't mess with the filename
// should work for all attachments, not just excel
$out = fopen("php://output", 'w'); // write directly to php output, not to a file
foreach($rows as $row)
{
fputcsv($out, $row);
}
fclose($out);
////////////////////////////////////////////////////////////////////////////////////////
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment