1

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!

Dan
  • 55,715
  • 40
  • 116
  • 154
  • 1
    If you do not need to process the results, you can start a [separate PHP process in the background](http://stackoverflow.com/questions/45953/php-execute-a-background-process) but PHP itself does not know the concept of asynchronous requests (because a PHP script runs from top to bottom as opposed to a JavaScript in the browser that can be triggered by events). That said, the [`curl_multi`](http://www.php.net/manual/en/function.curl-multi-select.php) family of functions does something that comes close – Pekka Mar 28 '11 at 09:53
  • http://www.onlineaspect.com/2009/01/26/how-to-use-curl_multi-without-blocking/ – Poelinca Dorin Mar 28 '11 at 09:56
  • thanks everyone, I'll chose the best method – Dan Mar 28 '11 at 10:12

2 Answers2

2

You can use curl_multi for this.

Dogbert
  • 212,659
  • 41
  • 396
  • 397
0

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

Perfection
  • 199
  • 1
  • 10