同时在每个循环中运行多个调用PHP?

问题描述:

我呼吁每个回路的功能在我的PHP代码这样的:同时在每个循环中运行多个调用PHP?

foreach ($tests as $test) { 
     $mytest = new Test; 
     $maintest = $mytest->Test_function($mytest); 

     $testarray[$test] = $mytest->getTest(); 
     } 

的$ mytest-每次调用> Test_function()可能需要约2分钟(对获取的数据远程服务器和测试呼叫)。

如果我有我的$测试数组5个元素,由脚本花费的时间为:〜= 5 * 2分钟 我知道PHP是不是一个异步的语言,但你知道的方式在同一时间推出全部5个电话?

这是非常令人沮丧得等待约10分钟,在和我的脚本^^

+0

我不知道这项服务,我会尝试一下,学习不是很难吗? – AlbertoV

+0

检查curl_multi_exec&curl_multi_select。发布“Test_function”的一些示例代码,也许我们可以帮助您重构代码。 –

这里是($ mytest的)的Test_function部分代码:

try { 
      $ch = curl_init(); 

      if (FALSE === $ch) 
       throw new Exception('failed to initialize'); 
      curl_setopt($ch, CURLOPT_URL, $mytest); 
      curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); 
      curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); 
      curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 
      curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); 
      curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10); 
      curl_setopt($ch, CURLOPT_MAXREDIRS, 2); 
      $agents = array(
       'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.7; rv:7.0.1) Gecko/20100101 Firefox/7.0.1', 
       'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.9) Gecko/20100508 SeaMonkey/2.0.4', 
       'Mozilla/5.0 (Windows; U; MSIE 7.0; Windows NT 6.0; en-US)', 
       'Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_7; da-dk) AppleWebKit/533.21.1 (KHTML, like Gecko) Version/5.0.5 Safari/533.21.1' 

      ); 
      curl_setopt($ch, CURLOPT_USERAGENT, $agents[array_rand($agents)]); 
      curl_setopt($ch, CURLOPT_HEADER, true); 

      $html = curl_exec($ch); 

      if (FALSE === $html) 
       throw new Exception(curl_error($ch), curl_errno($ch)); 

     } catch(Exception $e) { 

      trigger_error(sprintf(
       'Curl failed with error #%d: %s',$mytest, 
       $e->getCode(), $e->getMessage()), 
       E_USER_ERROR); 

     } 
     curl_close($ch); 
     $dom = new DOMDocument(); 
     @$dom->loadHTML($html); 

     $linklist= array(); 

     foreach($dom->getElementsByTagName('a') as $link) { 
      $href = $link->getAttribute('href'); 
      array_push($linklist, $href); 
     }