46 lines
1.1KB

  1. <?php
  2. namespace common\helpers;
  3. class CSV {
  4. public static function array2csv(array &$array) {
  5. if (count($array) == 0) {
  6. return null;
  7. }
  8. ob_start();
  9. $df = fopen("php://output", 'w');
  10. // clés
  11. //fputcsv($df, array_keys(reset($array)));
  12. foreach ($array as $row) {
  13. fputcsv($df, $row);
  14. }
  15. fclose($df);
  16. return ob_get_clean();
  17. }
  18. public static function downloadSendHeaders($filename) {
  19. // disable caching
  20. $now = gmdate("D, d M Y H:i:s");
  21. header("Expires: Tue, 03 Jul 2001 06:00:00 GMT");
  22. header("Cache-Control: max-age=0, no-cache, must-revalidate, proxy-revalidate");
  23. header("Last-Modified: {$now} GMT");
  24. // force download
  25. header("Content-Type: application/force-download");
  26. header("Content-Type: application/octet-stream");
  27. header("Content-Type: application/download");
  28. // disposition / encoding on response body
  29. header("Content-Disposition: attachment;filename={$filename}");
  30. header("Content-Transfer-Encoding: binary");
  31. }
  32. /*
  33. * usage
  34. * download_send_headers("data_export_" . date("Y-m-d") . ".csv");
  35. echo array2csv($array);
  36. die();
  37. */
  38. }