2011-04-20 3 views
1

curl_multi를 사용하여 일부 비동기 요청을 수행하려고하지만, 요청의 응답이 내 요구 사항을 채울 때 모든 요청을 중지하려고하기 때문에 그 당시에는 요청 그룹을 만들고 싶습니다. 여기 내 코드입니다 : 여기PHP에서 여러 curl_multi 요청을 동기화하는 방법은 무엇입니까?

//chunks the array into minor arrays 
$chunks = array_chunk($likes, 8); 
//Counter var 
$cont = 0; 
//Array of results 
$ofertas = array(); 
foreach ($chunks as $likes)  
{ 
    $codCategoria = $categorias[$categoria];  
    //In this function 'getOfertas' is the multi_curl request 
    $respostas = getOfertas($likes, $codCategoria);   
    //Iterates in the array of results of the multi_curl  
    foreach ($respostas as $json)  
    { 
     $resposta = json_decode($json, true); 
     //If the json obtained is no empty  
     if ($resposta['num_and'] > 0)  
     { 
      echo "cont: $cont <br>"; 
      //Increment counter and put the response into the array $ofertas 
      $cont++; 
      $i = array_rand($resposta['ofertas']); 
      $oferta = $resposta['ofertas'][$i]; 
      array_push ($ofertas, $oferta); 
      //If i have already 4 ou more results exit the loop, because i only need 4 of then 
      if ($cont >= 4) 
       break; 
     } 

    } 
} 

return $ofertas; 

는 curl_multi 코드 getOfertas 내부 함수는()입니다

function parallelGet($urls) 
{ 
    print_r($urls); 
    $res = array(); 
    // Create get requests for each URL 
    $mh = curl_multi_init(); 
    foreach($urls as $i => $url) 
    { 
     $ch[$i] = curl_init($url); 
     curl_setopt($ch[$i], CURLOPT_RETURNTRANSFER, 1); 
     curl_multi_add_handle($mh, $ch[$i]); 
     #echo "request "; 
    } 

    // Start performing the request 
    do { 
     $execReturnValue = curl_multi_exec($mh, $runningHandles); 
    } while ($execReturnValue == CURLM_CALL_MULTI_PERFORM); 
     // Loop and continue processing the request 
    while ($runningHandles && $execReturnValue == CURLM_OK) { 
     // Wait forever for network 
     $numberReady = curl_multi_select($mh); 
     if ($numberReady != -1) { 
     // Pull in any new data, or at least handle timeouts 
     do { 
      $execReturnValue = curl_multi_exec($mh, $runningHandles); 
     } while ($execReturnValue == CURLM_CALL_MULTI_PERFORM); 
     } 
    } 

    // Check for any errors 
    if ($execReturnValue != CURLM_OK) { 
     trigger_error("Curl multi read error $execReturnValue\n", E_USER_WARNING); 
    } 

    // Extract the content 
    foreach($urls as $i => $url) 
    { 
     // Check for errors 
     $curlError = curl_error($ch[$i]); 
     if($curlError == "") { 
     $res[$i] = curl_multi_getcontent($ch[$i]); 
     } else { 
     print "Curl error on handle $i: $curlError\n"; 
     } 
     // Remove and close the handle 
     curl_multi_remove_handle($mh, $ch[$i]); 
     curl_close($ch[$i]); 
    } 
    // Clean up the curl_multi handle 
    curl_multi_close($mh); 

    // Print the response data 
    return $res; 
} 

답변

관련 문제