PHP export csv file function (enhanced version)

WBOY
Release: 2016-07-25 08:55:04
Original
993 people have browsed it
  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


source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!