How to make multiple parallel Guzzle requests in PHP?

To make multiple parallel Guzzle requests in PHP, you can use Guzzle's Pool class along with Promise and wait methods. Here's an example:

use GuzzleHttp\Client; use GuzzleHttp\Pool; use GuzzleHttp\Psr7\Request; // Create a client instance $client = new Client(); // Create the requests array $requests = [ new Request('GET', 'https://example.com/request1'), new Request('GET', 'https://example.com/request2'), new Request('GET', 'https://example.com/request3'), // Add more requests as needed ]; // Create a pool of requests $pool = new Pool($client, $requests, [ // Set the concurrency limit (number of parallel requests) 'concurrency' => 5, // Optional callback to handle completed requests 'fulfilled' => function ($response, $index) { // Process the response of each completed request echo "Request {$index} completed: " . $response->getStatusCode() . "\n"; }, // Optional callback to handle rejected requests 'rejected' => function ($reason, $index) { // Handle any rejected requests, if needed echo "Request {$index} failed: " . $reason . "\n"; }, ]); // Initiate the transfer and wait for all responses $pool->promise()->wait();

In this example, we create a Client instance and define an array of Request objects. The Pool class is then used to manage and execute the requests concurrently. The concurrency option is set to determine the number of parallel requests. You can adjust this value according to your requirements.

The fulfilled callback is executed for each successful response, allowing you to process the response data. The rejected callback is executed for any rejected requests, providing an opportunity to handle any failures.

Finally, we call promise()->wait() to initiate the transfer and wait for all responses to complete.