php实现百万级数据导出至excel

设置服务器内存
设置程序运行的最大时间
如果导出数量过大,推荐使用循环导出,每次循环这里以导出一万条为例,循环100次即可全部导出

// 设置运行时间
set_time_limit(0);
// 设置内存
ini_set('memory_limit', '1024M');

$outformat = urlencode("测试数据");
header("Cache-control: private");
header("Pragma: public");
header('Content-type: application/x-csv');
if (strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE 5')) {
	header("Content-Disposition: inline; filename={$outformat}.csv");
} else {
	header("Content-Disposition: attachment; filename={$outformat}.csv");
    // 苹果电脑safari访问,解决文件名乱码
    header("Content-Disposition: attachment; filename*=utf-8''{$outformat}.csv");
}

$title = ['用户名', '年龄', '城市'];
$limit = 10000;
$page = 1;

$fp = fopen('php://output', 'a');
fputcsv($fp, $title);
while (true) {
	$start = ($page - 1) * $limit;
	$sql = "SELECT uname,age,city FROM `hd_test` ORDER BY `id` LIMIT {$start},{$limit}";
    $result = $pdo->query($sql);
	if (!$result) {
		break;
	}

	foreach ($result as $item) {
		fputcsv($fp, $data);
	}

    // 刷新缓冲区
	ob_flush();
	flush();

	++$page;
}

fclose($fp);