Dan
Dan

Reputation: 57881

Async requests in PHP

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!

Upvotes: 1

Views: 598

Answers (2)

Perfection
Perfection

Reputation: 199

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

Upvotes: 0

Dogbert
Dogbert

Reputation: 222040

You can use curl_multi for this.

Upvotes: 2

Related Questions