<?php
set_csv_header('test_max.csv'); //设置头部
$sql = "select id, name, sex,age from test"; //查询sql
ob_end_clean(); //清除内存
ob_start();
$per_limit = 20000; //每次取数据2w(大约2M的数据,可调整根据实际情况而定)
$query_count = ceil($total['count'] / $per_limit); //查询总次数
$fp = fopen('php://output', 'a'); //输出倒浏览器
$csv_header = ['id','姓名',性别','年龄'];
$is_windows = is_windows();
if ( $is_windows ) { //windows 转为gbk
$csv_header = array_map(function($item) {
return iconv('utf-8', 'gbk//TRANSLIT', $item);
}, $csv_header);
}
fputcsv($fp, $csv_header); //导出csv标题
//导出数据部分
for ($i = 0; $i < $query_count; $i++ ) {
$down_offset = $i * $per_limit;
$down_sql = $sql." OFFSET {$down_offset} LIMIT {$per_limit}";
$tmp = [];
$tmp = DB::GetQueryResult($down_sql, false); //查询数据库
foreach ($tmp as $val ) {
$val['name'] = str_replace(',', '、', $val['name']); //csv 默认使用英文逗号分割,替换字段里逗号,防止字段跨列展示
if ( $is_windows ) { //windows 转为gbk
$val = array_map(function($item) {
return iconv('utf-8', 'gbk//TRANSLIT', $item);
}, $val);
}
fputcsv($fp, $val);
}
ob_flush();
flush();
}
exit(0);
function is_windows() {
if ( stripos($_SERVER['HTTP_USER_AGENT'], 'windows') !== false) {
return true;
}
return false;
}
function set_csv_header($filename) {
set_time_limit(0); //防止超时
ini_set('memory_limit', '512M'); //防止内存溢出
header("Content-Type: text/csv; charset=UTF-8");
header("Content-Disposition:attachment;filename=" . $filename);
header('Cache-Control:must-revalidate,post-check=0,pre-check=0');
header('Expires:0');
header('Pragma:public');
}
PHP 超大csv浏览器下载
最新推荐文章于 2021-03-09 21:00:50 发布