优化csv导出函数

master
chenzhi 5 years ago
parent ab5f7267e5
commit cf89e73281

@ -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();
}

Loading…
Cancel
Save