From cf89e73281d12c7355063c7ba5f5b5e43254b754 Mon Sep 17 00:00:00 2001 From: chenzhi Date: Mon, 23 Dec 2019 14:35:14 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BC=98=E5=8C=96csv=E5=AF=BC=E5=87=BA?= =?UTF-8?q?=E5=87=BD=E6=95=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Application/Admin/Common/extend.php | 26 +++++++++++++++++++++----- 1 file changed, 21 insertions(+), 5 deletions(-) diff --git a/Application/Admin/Common/extend.php b/Application/Admin/Common/extend.php index ed683cdb6..4b85bbb1f 100644 --- a/Application/Admin/Common/extend.php +++ b/Application/Admin/Common/extend.php @@ -1726,30 +1726,46 @@ function getOffspringByPromoteId($promote_id = null) { } return $promote_ids; } -//导出csv 新增字段排序功能 +/** + * csv 导出函数 + * @param [array] $data 一般为数据库查询结果集 + * @param [string] $title 表格名称 + * @param [array] $fields [字段=>首行名称,...]例如:['name'=>'名称'] + * @return void + */ function data2csv(&$data,$title,$fields){ set_time_limit(0); + ini_set('memory_limit', '-1'); //设置内存不受限制 $filename = $title .'.csv'; $fp = fopen($filename, 'w'); //生成临时文件 fwrite($fp, chr(0xEF).chr(0xBB).chr(0xBF));//转码,防止乱码 - $field = array_keys($fields); + //生成首行 $header = array_values($fields); fputcsv($fp, $header); + + $index = 0; foreach ($data as $row) { $a = []; foreach($field as $k=>$v){ - $a[$v] = $row[$v]; + $a[$v] = $row[$v] . "\t";//防止格式错误 + } + if ($index == 10000) { //每次写入1000条数据清除内存 + $index = 0; + ob_flush();//清除内存 + flush(); } - fputcsv($fp, $a); + $index++; + fputcsv($fp, $a); } + ob_flush(); fclose($fp); //每生成一个文件关闭 //下载 header('Content-Type: application/vnd.ms-excel;charset=utf-8'); header('Content-Disposition: attachment;filename="' . $title . '.csv"'); header('Cache-Control: max-age=0'); header('Content-Length: ' . filesize($filename)); - readfile($filename); + @readfile($filename); unlink($filename); die(); }