【问题标题】:Export large MySQL table to CSV with PHP/PDO使用 PHP/PDO 将大型 MySQL 表导出为 CSV
【发布时间】:2016-11-04 06:17:25
【问题描述】:

我目前正在使用数组和 fputcsv 将 MySQL 表导出到 csv 文件。这很好用,但是我有一个表对于这种方法来说太大(100,000 + 行),所以我的网站超时了。

我当前的代码是;

<?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);        
?>

我读过一种可能的方法是从查询结果集中单独读取每个数据行并直接写入 php://output,然后读取下一行等;而不是构建一个大型数组或在内存中构建 csv。

我已经尝试了一些事情,但我在 for 循环中遇到了困难,因此非常感谢任何有关如何实现这一点的帮助。

【问题讨论】:

  • 既然可以直接使用 PHP,为什么还要这样做呢? stackoverflow.com/questions/356578/…
  • this 怎么样。对你有用吗?
  • 该页面上的示例仍将整个表加载到数组中,因此会导致相同的内存/超时问题。

标签: php mysql csv pdo


【解决方案1】:

检查您的 php.ini 文件 查找搜索最大值和折痕值,例如 max_execution_time 最大输入时间 最大输入变量 最大输入变量 post_max_size upload_max_filesize

【讨论】:

  • It's not hard to earn enough rep to make comments.。虽然这可能会回答问题,但提供有关为什么和/或如何回答问题的额外背景可以提高其长期价值。
  • 虽然不是我正在寻找的解决方案 PHP ini 允许我将现有代码用于大型表。我已将这两行添加到顶部; ini_set('memory_limit', '-1'); ini_set('max_execution_time', 0);
猜你喜欢
  • 1970-01-01
  • 2014-01-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-04-16
  • 1970-01-01
  • 2014-03-15
相关资源
最近更新 更多