Async requests in PHP

2019-08-02 21:33发布

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!

2条回答
兄弟一词,经得起流年.
2楼-- · 2019-08-02 21:57

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

查看更多
时光不老,我们不散
3楼-- · 2019-08-02 22:10

You can use curl_multi for this.

查看更多
登录 后发表回答