缓冲和非缓冲查询可用于有限数量的记录。
例如:在使用缓冲方式实现查询下载CSV时,超过30,000条记录需要缓冲,就会出现内存限制问题。
类似地,对于非缓冲方式,负载会转移到数据库服务器。
可以通过以下方法减少Web服务器(缓冲)和MySQL服务器(非缓冲)上的此负载,从而支持下载30,000+条记录的CSV。
<?php
// shell 命令 
$shellCommand = 'mysql '
 . '--host='.escapeshellarg($hostname).' '
 . '--user='.escapeshellarg($username).' ' 
 . '--password='.escapeshellarg($password).' '
 . '--database='.escapeshellarg($database).' ' 
 . '--execute='.escapeshellarg($sql).' '
 . '| sed -e \'s/"/""/g ; s/\t/","/g ; s/^/"/g ; s/$/"/g\'';
// CSV 头部 
header("Content-type: text/csv"); 
header("Content-Disposition: attachment; filename={$csvFilename}"); 
header("Pragma: no-cache"); 
header("Expires: 0");
// 通过 shell 执行命令并回显完整的输出作为字符串
echo shell_exec($shellCommand);
?>
sed正则表达式会消耗一些CPU。