2014-09-05 90 views
0

我的情況是這樣的,我有處理大量結果集的PHP

$data = $somearray; //say the number of records in this array is 200000 

IAM循環這個數據,處理一些功能和寫這個數據到Excel中的一個巨大的數據集從MySQL表提取文件​​

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

我的問題是,循環獲取內存耗盡......它顯示「的致命錯誤,允許內存大小..」反正是有處理這個循環沒有枯竭

由於服務器限制IM無法提高PHP內存限制像

ini_set("memory_limit","2048M"); 

我不是關注它takes..even的時間,如果它需要hours..so我做set_time_limit(0)

+0

難道你不能在批處理中讀取MySQL數據,還是按行逐行處理,而不是將整個集合保存到變量中? – Prix 2014-09-05 08:30:18

+0

我也嘗試過批處理......但它仍然掛起......有沒有辦法我們可以在每個循環結束時釋放內存 – coolguy 2014-09-05 08:33:34

+0

要釋放內存只需將變量設置爲null,垃圾收集器應該處理記憶。 – 2014-09-05 08:35:29

回答

1

如果您不必擔心時間,一次取1000行,並將行附加到文件的末尾,例如。創建一個臨時文件,在作業完成後移動和/或重命名。

First select count(*) from table 
    then for($i = 0; i < number of row; i = i + 1000){ 
    result = SELECT * FROM table LIMIT i,1000; # Retrieve rows 6-15 
    append to file = result 
} 
move and rename the file 

這是檸元的代碼,但這個過程應該工作

+0

查詢需要'order by',否則不能保證它會選擇下一批。它還假定數據不會改變。 – Marek 2014-09-05 08:57:57

+0

隨意使用編輯按鈕來改進我的建議,正如我所說的,它只是一個列表形式,而不是一個工作示例。 – 2014-09-05 09:01:33

2

你能在你的MySQL查詢中使用「限制」?

LIMIT子句可用於約束SELECT語句返回的行數。 LIMIT需要一個或兩個數字參數,它們都必須是非負整數常量(除了使用預準備語句時)。

使用兩個參數,第一個參數指定要返回的第一行的偏移量,第二個參數指定要返回的最大行數。初始行的偏移量爲0(不是1):

SELECT * FROM tbl LIMIT 5,10; #檢索行6-15

http://dev.mysql.com/doc/refman/5.0/en/select.html

5

你的工作是線性的,你不需要加載所有數據。如果將此文件發送給httpClient,則使用Unbuffered Query也使用php://stdout(不要臨時文件)。

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