代码之家  ›  专栏  ›  技术社区  ›  Phill Pafford

php curl“致命错误:允许的内存大小”用于大型数据集

  •  0
  • Phill Pafford  · 技术社区  · 16 年前

    我知道设置内存的选项

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

    但我想知道是否有更好的方法来查询数据?

    我有一个while循环,检查是否需要查询另外1000条记录。 使用偏移量作为起始记录编号,使用限制作为返回的记录,我搜索与我的数据请求匹配的所有记录。在我得到错误之前,我记录了大约10万条。

    现在,在测试过程中,我发现了“致命错误:允许的内存大小…”错误。我通过设置上面的in i_set()来阅读,以允许内存增加,但我想知道是否可以更好地对其进行编码?

    每次我在while循环中执行下面的代码时,内存使用量都会增长很大。即使我取消($curl)。我认为如果在下一个curl查询之前解析了结果之后,可以取消设置$result和$curl变量,那么就可以减少这个值。

    function getRequest($url,$user,$pwd) {
    
        $curl = curl_init();
    
        curl_setopt($curl, CURLOPT_VERBOSE, 1);
        curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 2);
        curl_setopt($curl, CURLOPT_HEADER, 0);
        curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_USERPWD, "$user:$pwd");
        curl_setopt($curl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
        curl_setopt($curl, CURLOPT_ENCODING, '');
        curl_setopt($curl, CURLOPT_URL, $url);
    
        $result = curl_exec($curl);
    
        $httpResponseCode = (int)curl_getinfo($curl, CURLINFO_HTTP_CODE);
    
        switch ($httpResponseCode) {
            case 500:
                // Send problem email
                break;
            case 200:
                // GET was good
                break;
            default:
                // Send problem email
                break;
        }    
        curl_close($curl);
        return $result;
    } 
    

    While Loop(超薄版)

    while($queryFlag) { // $queryFlag is TRUE
    
            // Check if we have more records to query, if not set $queryFlag to FALSE
    
            // Build cURL URL
    
            echo "Before Call Memory Usage: ".memory_get_usage()."\n";
            $resultXML  = getRequest($query,$user,$pass);
            echo "After Call Memory Usage: ".memory_get_usage()."\n";
    
            $results        = new ParseXMLConfig((string)$resultXML); // This is basically a class for $this->xml = simplexml_load_string($xml);
    
            // Loop through results and keep what  I'm looking for
            foreach($results as $resultsKey => $resultsData) {
                if(preg_match('|^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$|i', $resultsData)) {
                    $resultsArr["$resultsData"] = $resultsData;
                }
            }
    
        }
    

    一些记忆号码

    • 呼叫前内存使用:1819736
    • 呼叫后内存使用:2285344
    • 保留我需要的数据
    • 转储我不需要的数据
    • 下一个循环迭代
    • 呼叫前内存使用:2084128
    • 呼叫后内存使用:2574952
    2 回复  |  直到 16 年前
        1
  •  0
  •   codaddict    16 年前

    猜测 您使用的是不正确的 钥匙 对于 $resultsArr . 您使用的字符串与键和值相同。

    尝试改变

    $resultsArr["$resultsData"] = $resultsData
    

    $resultsArr[$resultsKey] = $resultsData
    
        2
  •  0
  •   Phill Pafford    16 年前

    定居:

    ini_set("memory_limit","30M");
    
    推荐文章