Import Export CSV routine for CakePHP


/ Published in: Other
Save to your folder(s)



Copy this code and paste it in your HTML
  1. // Exports CSV
  2. function exportCSV($where = NULL, $delimeter = ',')
  3. {
  4. $csv = '';
  5. $this->recursive = -1;
  6. $rows = $this->findAll($where);
  7. foreach($rows as $row)
  8. {
  9. $row[$this->name] = str_replace('\', '\\',
  10. $row[$this->name]);
  11. $row[$this->name] = str_replace($delimeter, '\' .
  12. $delimeter, $row[$this->name]);
  13. $csv .= implode($delimeter, $row[$this->name]) . chr(13);
  14. }
  15.  
  16. $csv = trim($csv);
  17. return $csv;
  18. }
  19.  
  20. // Imports CSV
  21. function importCSV($csv, $delimeter = ',')
  22. {
  23. $keys = $this->getFieldNames();
  24. $rows = array();
  25. $csv = trim($csv);
  26. $csv_rows = explode(chr(13), $csv);
  27.  
  28. foreach($csv_rows as $csv_row)
  29. {
  30. $csv_row = str_replace('\\', '\', $csv_row);
  31. $csv_row = str_replace('\' . $delimeter, chr(26), $csv_row);
  32. $row = explode($delimeter, $csv_row);
  33. $row = str_replace(chr(26), $delimeter, $row);
  34. $row = array_combine($keys, $row);
  35. $rows = array_merge_recursive($rows,
  36. array(array($this->name => $row)));
  37. }
  38.  
  39. return $rows;
  40. }
  41.  
  42. // Returns model fieldnames
  43. function getFieldNames()
  44. {
  45.  
  46. $names = array();
  47. $fields = $this->_schema;
  48.  
  49. foreach($fields as $key => $value)
  50. array_push($names, $key);
  51.  
  52. return $names;
  53. }
  54.  

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.