Posted By

smagic39 on 10/19/15


Tagged

csv


Versions (?)

Generating CSV


 / Published in: PHP
 

normal and toCSV

  1. <?php
  2. $csv = "";
  3. foreach ($data as $row) {
  4. $csv .= join(",", $row) . "n";
  5. }
  6. echo $csv;
  7. ?>
  8.  
  9. <?php
  10. function toCSV(array $data, array $colHeaders = array(), $asString = false) {
  11. $stream = ($asString)
  12. ? fopen("php://temp/maxmemory", "w+")
  13. : fopen("php://output", "w");
  14.  
  15. if (!empty($colHeaders)) {
  16. fputcsv($stream, $colHeaders);
  17. }
  18.  
  19. foreach ($data as $record) {
  20. fputcsv($stream, $record);
  21. }
  22.  
  23. if ($asString) {
  24. rewind($stream);
  25. $returnVal = stream_get_contents($stream);
  26. fclose($stream);
  27. return $returnVal;
  28. }
  29. else {
  30. fclose($stream);
  31. }
  32. }

Report this snippet  

You need to login to post a comment.