How to make asynchronous HTTP requests in PHP

后端 未结 18 2060
梦如初夏
梦如初夏 2020-11-22 02:13

Is there a way in PHP to make asynchronous HTTP calls? I don\'t care about the response, I just want to do something like file_get_contents(), but not wait for

18条回答
  •  醉酒成梦
    2020-11-22 03:05

    I find this package quite useful and very simple: https://github.com/amphp/parallel-functions

    It will load all 3 urls in parallel. You can also use class instance methods in the closure.

    For example I use Laravel extension based on this package https://github.com/spatie/laravel-collection-macros#parallelmap

    Here is my code:

        /**
         * Get domains with all needed data
         */
        protected function getDomainsWithdata(): Collection
        {
            return $this->opensrs->getDomains()->parallelMap(function ($domain) {
                $contact = $this->opensrs->getDomainContact($domain);
                $contact['domain'] = $domain;
                return $contact;
            }, 10);
        }
    

    It loads all needed data in 10 parallel threads and instead of 50 secs without async it finished in just 8 secs.

提交回复
热议问题