doujuan2688 2014-09-28 19:35
浏览 71
已采纳

PHP Multi Curl Request,在等待响应时做一些工作

Here's a typical multi-curl request example for PHP:

$mh = curl_multi_init();

foreach ($urls as $index => $url) {
    $curly[$index] = curl_init($url);
    curl_setopt($curly[$index], CURLOPT_RETURNTRANSFER, 1);
    curl_multi_add_handle($mh, $curly[$index]);
}

// execute the handles
$running = null;
do {
    curl_multi_exec($mh, $running);
    curl_multi_select($mh);
} while($running > 0);

// get content and remove handles
$result = array();
foreach($curly as $index => $c) {
    $result[$index] = curl_multi_getcontent($c);
    curl_multi_remove_handle($mh, $c);
}

// all done
curl_multi_close($this->mh);

The process involves 3 steps: 1. Preparing data 2. Sending requests and waiting until they're finished 3. Collecting responses

I'd like to split step #2 into 2 parts, first send all the requests and then collect all the response, and do some useful job instead of just waiting, for example, processing the responses of last group of requests.

So, how can I split this part of code

$running = null;
do {
    curl_multi_exec($mh, $running);
    curl_multi_select($mh);
} while($running > 0);

into separate parts?

  1. Send all the requests
  2. Do some another job while waiting
  3. Retrieve all the responses

I tried like this:

// Send the requests
$running = null;
curl_multi_exec($mh, $running);

// Do some job while waiting
// ...

// Get all the responses
do {
    curl_multi_exec($mh, $running);
    curl_multi_select($mh);
} while($running > 0);

but it doesn't seem to work properly.

  • 写回答

1条回答 默认 最新

  • doumei3828 2014-09-29 07:23
    关注

    I found the solution, here's how to launch all the requests without waiting the response

    do {
        curl_multi_exec($mh, $running);
    } while (curl_multi_select($mh) === -1);
    

    then we can do any other jobs and catch the responses any time later.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?