Posted By

jorisros on 02/18/11


Tagged

php csv


Versions (?)

Save persons as csv example


 / Published in: PHP
 

  1. <?php
  2.  
  3. $arrPerson['name'] = 'Piet';
  4. $arrPerson['lastname'] = 'Janse';
  5. $arrPerson['address'] = 'Thuisstraat 35';
  6. $arrPerson['zipcode'] = '1111AA';
  7. $arrPerson['email'] = '[email protected]';
  8.  
  9. $arrPersons[] = $arrPerson;
  10.  
  11. $arrPerson['name'] = 'Jan';
  12. $arrPerson['lastname'] = 'Slagerszoon';
  13. $arrPerson['address'] = 'Straat 135';
  14. $arrPerson['zipcode'] = '1111AA';
  15. $arrPerson['email'] = '[email protected]';
  16.  
  17. $arrPersons[] = $arrPerson;
  18.  
  19.  
  20. $strCSV = '';
  21.  
  22. //Create titles from first record
  23. if(is_array($arrPersons[0]))
  24. {
  25. foreach($arrPersons[0] as $strField => $strValue)
  26. {
  27. $arrColomns[] = $strField;
  28. }
  29. }
  30. $strCSV .= "'".implode("','", $arrColomns)."'
  31. ";
  32.  
  33.  
  34. //fill rows
  35. if(is_array($arrPersons))
  36. {
  37. $strRows = '';
  38.  
  39. foreach($arrPersons as $arrPerson)
  40. {
  41.  
  42. if(is_array($arrColomns))
  43. {
  44. $i = 0;
  45. $arrRow = array();
  46.  
  47. foreach($arrColomns as $strColomn)
  48. {
  49. $arrRow[] = $arrPerson[$strColomn];
  50. }
  51. $strCSV .= "'".implode("','",$arrRow)."'
  52. ";
  53.  
  54. }
  55. }
  56. }
  57.  
  58. header("Content-type: application/octet-stream");
  59. header("Content-Disposition: attachment; filename=\"persons.csv\"");
  60. echo $strCSV;

Report this snippet  

You need to login to post a comment.