php导出csv文件函数(增强版)
时间:2021-07-01 10:21:17
帮助过:30人阅读
/** - * 输出CSV的头信息
- * 注:使用此函数前后都不应有任何数据输出
- * @param $data Array 下载的数据
- * @param $file_name String 下载的文件名
- * @edit: bbs.it-home.org
- */
- function outputCsvHeader($data,$file_name = 'export')
- {
- header('Content-Type: text/csv');
- $str = mb_convert_encoding($file_name, 'gbk', 'utf-8');
- header('Content-Disposition: attachment;filename="' .$str . '.csv"');
- header('Cache-Control:must-revalidate,post-check=0,pre-check=0');
- header('Expires:0');
- header('Pragma:public');
- $csv_data = '';
- foreach ($data as $line)
- {
- foreach ($line as $key => &$item)
- {
- $item = str_replace (',',',',str_replace(PHP_EOL,'',$item)); //过滤生成csv文件中的(,)逗号和换行
- $item = mb_convert_encoding($item, 'gbk', 'utf-8');
- }
- $csv_data .= implode(',', $line) . PHP_EOL;
- }
- echo $csv_data;
- }
//php导出csv文件示例 - outputCsvHeader($data,"myfile.csv");
|