Async requests in PHP

2019-08-02 21:43发布

问题:

I need to generate requests to several APIs, get response from them and then generate a report.

something like this:

foreach($api_array as $api){
    echo $api;

    $responce = file_get_contents($api);

    if($responce) 
        echo 'ok <br/>';
    else 
        echo 'fail <br/>';
}

It's obvious that when run consistently, one by one, this will take A LOT of time to wait for each service to respond.

Can this be done asynchronously, like in JavaScript? Thanks a lot!

回答1:

You can use curl_multi for this.



回答2:

Yes you can do that using curl_multi that will do it in parallel. You can also use a callback to get the reponses like in this example http://curl.haxx.se/libcurl/php/examples/callbacks.html

Also read more on curl_multi here http://php.net/manual/en/function.curl-multi-init.php2