简体   繁体   English

使用PHP / PDO将大型MySQL表导出为CSV

[英]Export large MySQL table to CSV with PHP/PDO

I am currently using arrays and fputcsv to export MySQL tables to a csv file. 我目前正在使用数组和fputcsv将MySQL表导出到csv文件。 This works great, however I have one table which is too large (100,000 + rows) for this method and so my site times out. 这很好用,但是对于这种方法,我有一个表太大(100,000 +行),所以我的网站超时了。

My current code is; 我当前的代码是;

<?php                                    
//open database connection                            
require ('../database-config.php');
header('Content-Type: text/csv');
header('Content-Disposition: attachment;filename=exported_archive_all.csv');

//SQL Query for Data
$sql = "SELECT * FROM inverter_data_archive;";        
//Prepare Query, Bind Parameters, Excute Query
$STH = $dbh->prepare($sql);
$STH->execute();

//Export to .CSV
$fp = fopen('php://output', 'w');

// first set
$first_row = $STH->fetch(PDO::FETCH_ASSOC);
$headers = array_keys($first_row);
fputcsv($fp, $headers); // put the headers
fputcsv($fp, array_values($first_row)); // put the first row

while ($row = $STH->fetch(PDO::FETCH_NUM))  {
fputcsv($fp,$row); // push the rest
}
fclose($fp);        
?>

I have read that a possible approach is to read each data row individually from the query result set and write directly to php://output, then read the next row, etc; 我已经读过一种可能的方法是从查询结果集中分别读取每个数据行,然后直接写入php:// output,然后读取下一行,依此类推; rather than building a large array or building the csv in memory. 而不是构建大型数组或在内存中构建csv。

I've tried a few things but I struggle with for loops so any help on how to achieve this would be much appreciated. 我已经尝试了一些方法,但是我为for循环而苦苦挣扎,因此,对实现该方法的任何帮助将不胜感激。

检查您的php.ini文件查找搜索最大值和折痕值,例如max_execution_time max_input_time max_input_vars max_input_vars post_max_size upload_max_filesize

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM