【发布时间】:2014-05-26 05:51:58
【问题描述】:
我正在做一个项目,我需要从包含近 10k 行的数据库中提取数据,然后将其导出为 CSV。我尝试了正常的方法来下载 CSV,但即使我们已经将 memory_limit 设置为 256MB,我也总是遇到内存限制问题。
如果你们中的任何人遇到过同样的问题,请分享您对最佳解决方案或方法的看法。
真的很感谢你们的想法。
这是我的实际代码:
$filename = date('Ymd_His').'-export.csv';
//output the headers for the CSV file
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header('Content-Description: File Transfer');
header("Content-type: text/csv");
header("Content-Disposition: attachment; filename={$filename}");
header("Expires: 0");
header("Pragma: public");
//open the file stream
$fh = @fopen( 'php://output', 'w' );
$headerDisplayed = false;
foreach ( $formatted_arr_data_from_query as $data ) {
// Add a header row if it hasn't been added yet -- using custom field keys from first array
if ( !$headerDisplayed ) {
fputcsv($fh, array_keys($ccsve_generate_value_arr));
$headerDisplayed = true;
}
// Put the data from the new multi-dimensional array into the stream
fputcsv($fh, $data);
}
// Close the file stream
fclose($fh);
【问题讨论】:
-
您是否使用无缓冲查询?你用 fputcsv() 写你的行吗?
-
从查询结果集中单独读取每个数据行并直接写入php://output,然后读取下一行等;而不是构建任何大型数组或在内存中构建 csv
-
1.您是否使用
echo向浏览器发送数据? 2. 您是否要求浏览器通过 HTTP 标头下载文件 3. 您如何从数据库中获取数据? -
您是否考虑过使用
mysqldumpsystem命令。这解决了我过去的所有问题。 -
@rosscowar mysqdump 不适用于我,因为我需要在添加到 CSV 之前格式化数据。
标签: php mysql ajax export-to-csv large-data