Export MySQL query results to CSV


/ Published in: PHP



Copy this code and paste it in your HTML
  1. // Export to CSV
  2. if($_GET['action'] == 'export') {
  3.  
  4. $rsSearchResults = mysql_query($sql, $db) or die(mysql_error());
  5.  
  6. $out = '';
  7. $fields = mysql_list_fields('database','table',$db);
  8. $columns = mysql_num_fields($fields);
  9.  
  10. // Put the name of all fields
  11. for ($i = 0; $i < $columns; $i++) {
  12. $l=mysql_field_name($fields, $i);
  13. $out .= '"'.$l.'",';
  14. }
  15. $out .="\n";
  16.  
  17. // Add all values in the table
  18. while ($l = mysql_fetch_array($rsSearchResults)) {
  19. for ($i = 0; $i < $columns; $i++) {
  20. $out .='"'.$l["$i"].'",';
  21. }
  22. $out .="\n";
  23. }
  24. // Output to browser with appropriate mime type, you choose ;)
  25. header("Content-type: text/x-csv");
  26. //header("Content-type: text/csv");
  27. //header("Content-type: application/csv");
  28. header("Content-Disposition: attachment; filename=search_results.csv");
  29. echo $out;
  30. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.