2013-10-25 5 views
1

curl_multi_init으로 시도하면 페이지 정보가 표시됩니다. 하지만 curl_multi_getcontent() - 30s 후에 페이지 정보를 얻으려고하면. 하위. curl_multi_getcontent()를 올바르게 사용해야하는 방법은 무엇입니까? 감사합니다php - curl multi, 매우 느려서 콘텐츠를 얻으려고 시도 할 때

class Grab 
{ 
    public function getData() 
    { 
     $sessions = array('111', '222', '333', '444', '555'); 

     $handle = curl_init(); 

     foreach($sessions as $sId) { 
      $sessionId = $sId; 

      echo $sessionId.'<br/>'; 

      $url = 'https://www.mypage.com?id='.$sessionId.'&test=1'; 

      curl_setopt($handle, CURLOPT_URL, $url); 
      curl_setopt($handle, CURLOPT_RETURNTRANSFER, true); 
      curl_setopt($handle, CURLOPT_FRESH_CONNECT, false); 
      curl_setopt($handle, CURLOPT_SSL_VERIFYPEER, false); 
      curl_setopt($handle, CURLOPT_FAILONERROR, true); 

      $sResponse = $this->curlExecWithMulti($handle); 
     } 
    } 

    function curlExecWithMulti($handle) { 
     // In real life this is a class variable. 
     static $multi = NULL; 

     // Create a multi if necessary. 
     if (empty($multi)) { 
      $multi = curl_multi_init(); 
     } 

     // Add the handle to be processed. 
     curl_multi_add_handle($multi, $handle); 

     // Do all the processing. 
     $active = NULL; 
     do { 
      $ret = curl_multi_exec($multi, $active); 
     } while ($ret == CURLM_CALL_MULTI_PERFORM);  

     while ($active && $ret == CURLM_OK) { 
      if (curl_multi_select($multi) != -1) { 
       do { 
        $mrc = curl_multi_exec($multi, $active); 

       } while ($mrc == CURLM_CALL_MULTI_PERFORM); 
      } 
     } 

     **$res = curl_multi_getcontent($handle); // - very slow** 
     $this->printData($res); 

     // Remove the handle from the multi processor. 
     curl_multi_remove_handle($multi, $handle); 

     return TRUE; 
    } 

    public function printData($res) 
    { 
      $oPayment = json_decode($res); 

      var_dump($oPayment); 
      var_dump($errorno); 
      echo '<br/>---------------------<br/>'; 
    } 
} 

$grab = new Grab; 
$grab->getData(); 

답변

1

모든 $ handle에 대해 foreach 루프에서 curlExecWithMulti를 호출하면 안됩니다. 당신은 핸들 배열을 생성하고, curl_multi_add_handle에 의해 핸들을 추가해야하며, 그 후에는 모든 처리를 수행해야한다 (curl_multi_exec 루프). 처리가 끝나면 curl_multi_getcontent를 사용하여 루프의 모든 결과를 읽을 수 있습니다.

그것은처럼 보일 것이다 :

$handles = array(); 

    foreach($sessions as $sId) { 
     $handle = curl_init(); 
     $sessionId = $sId; 

     echo $sessionId.'<br/>'; 

     $url = 'https://www.mypage.com?id='.$sessionId.'&test=1'; 

     curl_setopt($handle, CURLOPT_URL, $url); 
     curl_setopt($handle, CURLOPT_RETURNTRANSFER, true); 
     curl_setopt($handle, CURLOPT_FRESH_CONNECT, false); 
     curl_setopt($handle, CURLOPT_SSL_VERIFYPEER, false); 
     curl_setopt($handle, CURLOPT_FAILONERROR, true); 

     $handles[] = $handle; 
    } 

    // calling curlExecWithMulti once, passing array of handles 
    // and got array of results 
    $sResponse = $this->curlExecWithMulti($handles);