csv因为是文本格式,可支持大文件
csv :文件, 文本格式, 字段间逗号分隔, 可用excel打开
EXCEL2007之前只能显示6.4W行, 2007之后, 可以支持104W行
/**
* 导出大数据到CSV, 当前页面下载, 弊端,EXCEL最多支持108万行.几百万级的数据读不了
*/
set_time_limit(0);
header ( "Content-type:application/vnd.ms-excel" );
header ( "Content-Disposition:filename=" . iconv ( "UTF-8", "GB18030", "query_user_info" ) . ".csv" );
// 打开PHP文件句柄,php://output 表示直接输出到浏览器
$fp = fopen('php://output', 'a');
$column_name = array('id','ZONEID','USERID','TIME');//标题
// 将中文标题转换编码,否则乱码
foreach ($column_name as $i => $v) {
$column_name[$i] = iconv('utf-8', 'GB18030', $v);
}
// 将标题名称通过fputcsv写到文件句柄
fputcsv($fp, $column_name);
include_once "database.php";
//总数
//$con = mysqli_connect('127.0.0.1','root','hoolai','Log','3306');
$con = mysqli_connect(DATABASE_HOST,DATABASE_USER,DATABASE_PASS,DB_LOG,DATABASE_PORT);
$con ? '': 'error:'.mysqli_error($con);
$result = mysqli_query($con,"select count(1) as total from LOG_CURRENCY");
$count1 = mysqli_fetch_assoc($result);
$total_export_count = ($count1['total'] > 1000000) ? 1000000 : $count1['total'] ;//总数 小于等于100W
$pre_count = 10000;
for ($i=0;$i<intval($total_export_count/$pre_count)+1;$i++){
$result2 = mysqli_query($con,"select ID,ZONEID,USERID,TIME from LOG_CURRENCY LIMIT ".$i*$pre_count.",$pre_count");
$export_data = array();
// $export_data = mysqli_fetch_all($result2,MYSQLI_ASSOC);//线上环境不支持
while ($arow = mysqli_fetch_assoc($result2)){
$export_data[] = $arow;
}
// $export_data = $db->getAll($sql." limit ".strval($i*$pre_count).",{$pre_count}");
// dump($export_data);die();
foreach ( $export_data as $item ) {
$rows = array();
foreach ( $item as $export_obj){
$rows[] = iconv('utf-8', 'GB18030', $export_obj);
}
fputcsv($fp, $rows);
}
// 将已经写到csv中的数据存储变量销毁,释放内存占用
unset($export_data);
ob_flush();
flush();
}
fclose($fp); //每生成一个文件关闭
exit ();