Posted By

damanlovett on 08/20/10


Tagged

cakephp csv export


Versions (?)

Who likes this?

5 people have marked this snippet as a favorite

damanlovett
zingo
rascoop
widgetyegg
Plotarius


CakePHP CSV export Controller


 / Published in: PHP
 

URL: http://gist.github.com/535882

  1. <?php
  2.  
  3. /**
  4.  *
  5.  * Dynamically generates a .csv file by looping through the results of a sql query.
  6.  *
  7.  */
  8.  
  9. function export()
  10. {
  11. ini_set('max_execution_time', 600); //increase max_execution_time to 10 min if data set is very large
  12.  
  13. //create a file
  14. $filename = "export_".date("Y.m.d").".csv";
  15. $csv_file = fopen('php://output', 'w');
  16.  
  17. header('Content-type: application/csv');
  18. header('Content-Disposition: attachment; filename="'.$filename.'"');
  19.  
  20. $results = $this->ModelName->query($sql); // This is your sql query to pull that data you need exported
  21. //or
  22. $results = $this->ModelName->find('all', array());
  23.  
  24. // The column headings of your .csv file
  25. $header_row = array("ID", "Received", "Status", "Content", "Name", "Email", "Source", "Created");
  26. fputcsv($csv_file,$header_row,',','"');
  27.  
  28. // Each iteration of this while loop will be a row in your .csv file where each field corresponds to the heading of the column
  29. foreach($results as $result)
  30. {
  31. // Array indexes correspond to the field names in your db table(s)
  32. $row = array(
  33. $result['ModelName']['id'],
  34. $result['ModelName']['received'],
  35. $result['ModelName']['status'],
  36. $result['ModelName']['content'],
  37. $result['ModelName']['name'],
  38. $result['ModelName']['email'],
  39. $result['ModelName']['source'],
  40. $result['ModelName']['created']
  41. );
  42.  
  43. fputcsv($csv_file,$row,',','"');
  44. }
  45.  
  46. fclose($csv_file);
  47. }
  48. ?>

Report this snippet  

Comments

RSS Icon Subscribe to comments
Posted By: melvin on February 10, 2011

the function didnt work

You need to login to post a comment.