为解决内存超出问题,修改PHP.ini limit_momery 不起做用 可采用分页写写数据到文件内 代码下
header('Content-Description: File Transfer'); header('Content-Type: application/vnd.ms-excel'); header('Content-Disposition: attachment; filename="'. $file .'"'); header('Expires: 0'); header('Cache-Control: must-revalidate'); header('Pragma: public'); $columns = [ 'ID','报警','设备名称','设备类型','开始时间','结束时间','描述','处理方式','责任等级','处理结果' ];
$fp = fopen('php://output', 'a');//打开output流 mb_convert_variables('GBK', 'UTF-8', $columns); fputcsv($fp, $columns); //将数据格式化为CSV格式并写入到output流中 $total = Alarm::getTotal($payload); $pageSize = 5000; $pages = ceil($total / $pageSize); for ($page = 1;$page <= $pages ;$page ++){ $offset = ($page-1)*$pageSize; $payload['offset'] = $offset; $payload['limit'] = $pageSize; $list = Alarm::getList($payload); foreach ($list as $alarm){ $row [] = $alarm['id']; mb_convert_variables('GBK', 'UTF-8', $row); fputcsv($fp, $row); unset($row); } if(ob_get_level()>0) ob_flush() ; flush(); } exit();
这样下载的数据可以达到几十万条