CsvHelper.php 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. <?php
  2. /**
  3. * Created by PhpStorm.
  4. * User: Administrator
  5. * Date: 2022/8/10
  6. * Time: 17:23
  7. */
  8. namespace file;
  9. class CsvHelper
  10. {
  11. /**
  12. * 解析csv
  13. * @param $filepath [文件完整路径]
  14. * @return array [返回二维数组,解析结果]
  15. */
  16. public static function parse_csv($filepath)
  17. {
  18. $handle = fopen($filepath, 'r');//只读方式打开,将文件指针指向文件头]
  19. $out = array();
  20. $n = 0;
  21. while ($data = fgetcsv($handle, 10000)) {
  22. $num = count($data);
  23. for ($i = 0; $i < $num; $i++) {
  24. $row = mb_convert_encoding($data[$i], "UTF-8", "GBK");
  25. $out[$n][$i] = $row;
  26. }
  27. $n++;
  28. }
  29. fclose($handle); //关闭指针
  30. return $out;
  31. }
  32. /**
  33. * 导出csv
  34. * @param $titles [标题-数组]
  35. * @param $data [内容-二维数组]
  36. * @param string $filename [文件名]
  37. */
  38. public static function export_csv($titles, $data, $filename = "")
  39. {
  40. if (empty($filename)) {
  41. $filename = date('Ymd') . '.csv';
  42. }
  43. $str = "";
  44. if ($titles && is_array($titles)) {
  45. foreach ($titles as $title) {
  46. $str .= (empty($str) ? "" : ",") . $title;
  47. }
  48. $str = iconv('utf-8', 'gb2312', $str . PHP_EOL);
  49. }
  50. if ($data && is_array($data)) {
  51. foreach ($data as $line) {
  52. $line_str = "";
  53. foreach ($line as $row) {
  54. $row_ = mb_convert_encoding($row, "GBK", "UTF-8");
  55. $line_str .= (empty($line_str) ? "" : ",") . $row_;
  56. }
  57. $str .= $line_str . PHP_EOL;
  58. }
  59. }
  60. header("Content-type:text/csv");
  61. header("Content-Disposition:attachment;filename=" . $filename);
  62. header('Cache-Control:must-revalidate,post-check=0,pre-check=0');
  63. header('Expires:0');
  64. header('Pragma:public');
  65. exit($str);
  66. }
  67. }