【问题标题】:How to write millions of data using bucket system in php如何在php中使用桶系统写入数百万条数据
【发布时间】:2018-03-04 09:33:28
【问题描述】:

我尝试了一个小时,但找不到解决方案。我有 6000 万或更多然后记录(mysql)我想导出为 CSV 文件。请告诉我如何在此过程中使用铲斗系统。如果可以导出单独的文件对我有好处。

<?php
// Fetch Record from Database
@ini_set('log_errors','On');
@ini_set('display_errors','On');
@ini_set('error_log','error.log'); // path to server-writable log file
@ini_set('max_execution_time', 0); //unlimited
@ini_set('memory_limit', '-1');
$output = "";
$connection= mysqli_connect('192.168.1.203','cnsdb','cnsdb','test_irmt');
$table = "tracking";
$sql = mysqli_query($connection,"select * from {$table} limit 0,2000");
$columns_total = mysqli_num_fields($sql);

// Get The Field Name
$query = "SHOW COLUMNS FROM {$table}";
$result_set = mysqli_query($connection,$query);
while ($result = mysqli_fetch_array($result_set)) {
    $heading = $result[0];
    $output .= trim($heading.',');
}

$output = substr($output,0,strlen($output)-1)."\r\n";

// Get Records from the table


// Download the file

$filename = "output".".csv";
header("Pragma: public", true);
header("Expires: 0"); // set expiration time
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Content-Type: application/force-download");
header("Content-Type: application/octet-stream");
header("Content-Type: application/download");
header('Content-Disposition: attachment; filename='.$filename);
header("Content-Transfer-Encoding: binary");
header('Connection: Keep-Alive');

while ($row = mysqli_fetch_array($sql)) {
    for ($i = 0; $i < $columns_total; $i++) {
        $output .='"'.$row["$i"].'",';
    }
    $output = substr($output,0,strlen($output)-1)."\r\n";
}
echo $output;
exit;

?>

【问题讨论】:

  • Dump a mysql database to a plaintext (CSV) backup from the command line 的可能副本 SELECT * INTO OUTFILE 是您的繁重朋友。
  • 使用这种方法,您在发送之前在内存中创建整个 csv 文件,我猜您没有那么多可用内存。在生成 csv 时将其发送出去,而不是在发送之前将其全部存储在 ram 中
  • 您的用户真的希望将 6000 万条记录转储到他们的浏览器吗?至少(如果你必须在 PHP 中这样做)使用内置的 fputcsv() 函数
  • @ficuscr - 我试过了,但我只能导出 1000 万条记录
  • @MarkBaker 是否可以为每个 CSV 拆分 1M 记录。

标签: php mysql export large-data bucket


【解决方案1】:

示例尝试使用这个

SELECT *
INTO OUTFILE 'file.csv' -- Change the filename here
FIELDS
  TERMINATED BY ','
  OPTIONALLY ENCLOSED BY '"'
  ESCAPED BY '\\'
  LINES TERMINATED BY '\n'
FROM table

WHERE id BETWEEN 0 AND 10000000

根据需要更改上限/下限

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-09-13
    • 2016-01-29
    • 2015-09-04
    • 1970-01-01
    • 2012-05-16
    • 1970-01-01
    • 2023-01-31
    • 1970-01-01
    相关资源
    最近更新 更多