2017-02-23 116 views
0

我呼籲每個迴路的功能在我的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」的一些示例代碼,也許我們可以幫助您重構代碼。 –

回答

0

這裏是($ 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); 
     }