Posted By

mikegreen on 01/15/09


Tagged

mysql php csv excel spreadsheet


Versions (?)

Who likes this?

12 people have marked this snippet as a favorite

luman
jonniespratley
fackz
umang_nine
Hollow
vali29
jealousy
jcroom
nublaii
Nahit
ringo380
Priestd09


Export MySQL Data as CSV


 / Published in: PHP
 

Export MySQL Data as CSV

This code takes a mysql_query() resource and outputs its rows into CSV spreadsheet format. Edit the header('Content-Disposition... declaration to tell the user's browser to either display the data as plain text or download it as an attachment.

Note: This doesn't include the code to connect to the database in the first place. Don't forget that, otherwise this code is pretty useless.

  1. $result = mysql_query("SELECT * FROM table ORDER BY column DESC");
  2.  
  3. // I hard-code the column names so I can capitalize, add spaces, etc.
  4. $fields = '"User ID","Name","Email","Registration Date"'."\n";
  5.  
  6. // Iterate through the rows of data
  7. while ($row = mysql_fetch_assoc($result))
  8. {
  9. $fields .= '"'.$row['id'].'","'.$row['name'].'","'.$row['email'].'","'.$row['registration_date'].'"'."\n";
  10. }
  11.  
  12. // Set our headers
  13. header('Content-type: text/csv');
  14. // To display data in-browser, change the header below to:
  15. // header("Content-Disposition: inline");
  16. header("Content-Disposition: attachment; filename=event_registrations.csv");
  17.  
  18. // Output our data
  19. echo $fields;

Report this snippet  

You need to login to post a comment.