导出CSV文件
1 /** 2 * 导出CSV文件 3 * @param array $data 数据 4 * @param array $header_data 首行数据 5 * @param string $file_name 文件名称 6 * @return string 7 */ 8 function export_csv($data = [], $header_data = [], $file_name = ''){ 9 header('Content-Type: application/vnd.ms-excel'); 10 header('Content-Disposition: attachment;filename='.$file_name); 11 header('Cache-Control: max-age=0'); 12 $fp = fopen('php://output', 'a'); 13 if (!empty($header_data)) { 14 foreach ($header_data as $key => $value) { 15 $header_data[$key] = iconv('utf-8', 'gbk', $value); 16 } 17 fputcsv($fp, $header_data); 18 } 19 $num = 0; 20 //每隔$limit行,刷新一下输出buffer,不要太大,也不要太小 21 $limit = 1000; 22 //逐行取出数据,不浪费内存 23 $count = count($data); 24 if ($count > 0) { 25 for ($i = 0; $i < $count; $i++) { 26 $num++; 27 //刷新一下输出buffer,防止由于数据过多造成问题 28 if ($limit == $num) { 29 ob_flush(); 30 flush(); 31 $num = 0; 32 } 33 $row = $data[$i]; 34 foreach ($row as $key => $value) { 35 $row[$key] = iconv('utf-8', 'gbk', $value); 36 } 37 fputcsv($fp, $row); 38 } 39 } 40 fclose($fp); 41 }