Make CSV File from Database

This is the easiest way to make a CSV file from a database query and output it to the user for download. This simple code uses the PHP5 fputcsv function to correctly format an array of values into a line in a csv file. It does not use the physical file so you do not need any write permissions where you use this code, as it uses the memory buffer instead.

PHP:
  1. $output = fopen('php://output', 'w');
  2.  
  3. $query = mysql_query("SELECT * FROM `table`");
  4. while ($data = mysql_fetch_assoc($query)){
  5.    
  6.     $record = array();
  7.     $record[] = $data['param1'];
  8.     $record[] = $data['param2'];
  9.     $record[] = $data['param3'];
  10.    
  11.     fputcsv($output, $record);
  12. }
  13.  
  14. fclose($output);
  15.  
  16. $output = file_get_contents($output);
  17.  
  18. header('Content-type: application/octet-stream');
  19. header('Content-Disposition: attachment; filename="export.csv"');
  20.  
  21. echo $output;

These icons link to social bookmarking sites where readers can share and discover new web pages.
  • Digg
  • del.icio.us
  • Netvouz
  • DZone
  • Reddit
  • Furl
  • NewsVine
  • Simpy
  • Slashdot
  • Spurl
  • StumbleUpon
  • YahooMyWeb
  • TailRank

Home | MySQL | Make CSV File from Database