Reputation: 998
I have a PHP script that needs to make three separate API calls, combine the results, and output it for the user.
The problem is that each API call takes about 5 seconds to execute. With 3 API calls at 5 seconds each, it take about 15 seconds to execute the script.
Is there a way that I can somehow start the three API calls simultaneously and once the last one finishes, combine the results? If that's possible I could potentially reduce the length of time from 15 to 5 seconds, dramatically improving my user's experience.
I researched asynchronous function calls in PHP, but there doesn't seem to be a lot of good options. I'm hoping that someone out there has been in a similar situation and found an elegant way to handle this.
Upvotes: 2
Views: 2522
Reputation: 17148
That's the entire answer, as short as it is: yes, in exactly the way you imagine it should ( I hope ).
Upvotes: 0
Reputation: 14128
PHP scripts by themselves are single threaded. There are ways to "fork" child processes in PHP using pcntl_fork function. But as far as I know, this only really works well with the CLI sapi. With any of the web server sapi's, either it's buggy or not supported.
If you have to initiate it from a web request, you could try using shell_exec to spawn a master PHP CLI process in the background (append &
at the end), and then make use of pcntl_fork to divide up the work.
If you're just waiting on web requests, I would follow Dagon's suggestion of using the curl_multi functions. But forking can be useful if you have other intensive tasks, if used correctly.
Upvotes: 1