使用php处理大型结果集

coo*_*guy 0 php loops memory-management out-of-memory

我的场景是这样的,我有一个从mysql表中获取的巨大数据集

$data = $somearray; //say the number of records in this array is 200000
Run Code Online (Sandbox Code Playgroud)

iam循环这些数据,处理一些功能并将这些数据写入excel文件

 $my_file = 'somefile.csv';
 $handle = fopen($my_file, 'w') or die('Cannot open file:  ' . $my_file); file
     for($i=0;$i<count($data);$i++){
         //do something with the data
         self::someOtherFunctionalities($data[$i]); //just some function    
         fwrite($handle, $data[$i]['index']); //here iam writing this data to a file
      }
 fclose($handle);
Run Code Online (Sandbox Code Playgroud)

我的问题是循环得到内存耗尽...它显示" 致命错误允许内存大小... "无论如何都是在没有耗尽的情况下处理这个循环

由于服务器的限制我无法增加php内存限制

ini_set("memory_limit","2048M");
Run Code Online (Sandbox Code Playgroud)

我不关心它需要的时间..即使它需要几个小时......所以我做了 set_time_limit(0)

Maj*_*eri 5

你的工作是线性的,你不需要加载所有数据.使用无缓冲的查询也使用PHP://标准输出(没有临时文件),如果这个文件发送到HttpClient的.

<?php
$mysqli  = new mysqli("localhost", "my_user", "my_password", "world");
$uresult = $mysqli->query("SELECT Name FROM City", MYSQLI_USE_RESULT);
$my_file = 'somefile.csv'; // php://stdout
$handle = fopen($my_file, 'w') or die('Cannot open file:  ' . $my_file); file

if ($uresult) {
   while ($row = $uresult->fetch_assoc()) {
   // $row=$data[i]
      self::someOtherFunctionalities($row); //just some function    
     fwrite($handle, $row['index']); //here iam writing this data to a file
   }
}
$uresult->close();
?>
Run Code Online (Sandbox Code Playgroud)