Home  >  Article  >  Backend Development  >  PHP export csv file function (enhanced version)

PHP export csv file function (enhanced version)

WBOY
WBOYOriginal
2016-07-25 08:55:04994browse
  1. /**

  2. * Output CSV header information
  3. * Note: There should be no data output before and after using this function
  4. * @param $data Array Downloaded data
  5. * @param $file_name String Downloaded file name
  6. * @edit: bbs. it-home.org
  7. */
  8. function outputCsvHeader($data,$file_name = 'export')
  9. {
  10. header('Content-Type: text/csv ');
  11. $str = mb_convert_encoding($file_name, 'gbk', 'utf-8');
  12. header('Content-Disposition: attachment;filename="' .$str . '.csv"');
  13. header ('Cache-Control:must-revalidate,post-check=0,pre-check=0');
  14. header('Expires:0');
  15. header('Pragma:public');
  16. $csv_data = '' ;
  17. foreach ($data as $line)
  18. {
  19. foreach ($line as $key => &$item)
  20. {
  21. $item = str_replace (',',',',str_replace(PHP_EOL,'', $item)); //Filter (,) commas and line breaks in the generated csv file
  22. $item = mb_convert_encoding($item, 'gbk', 'utf-8');
  23. }
  24. $csv_data .= implode(', ', $line) . PHP_EOL;
  25. }
  26. echo $csv_data;
  27. }

  28. //Example of php exporting csv file

  29. outputCsvHeader($data,"myfile.csv");
Copy code


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn