Search code examples
phphttpcurlguzzlegoutte

Simultaneous HTTP requests with goutte


I know goutte is built on top of guzzle. Here's a sample of simultaneous HTTP requests with guzzle.

<?php
$client->send(array(
    $client->get('http://www.example.com/foo'),
    $client->get('http://www.example.com/baz'),
    $client->get('http://www.example.com/bar')
));

Can simultaneous requests be run through goutte too?


Solution

  • Just looking over Goutte's code real quick shows that it does not support multiple requests.

    However if you'd like, you can imitate Goutte by collecting the Guzzle requests and creating a new Symfony\Component\BrowserKit\Response object, which is what Goutte returns for the user to interact with.

    Check out their createResponse() function (which is unfortunately protected) for more information.

    <?php
    
    // Guzzle returns an array of Responses.
    $guzzleResponses = $client->send(array(
        $client->get('http://www.example.com/foo'),
        $client->get('http://www.example.com/baz'),
        $client->get('http://www.example.com/bar')
    ));
    
    // Iterate through all of the guzzle responses.
    foreach($guzzleResponses as $guzzleResponse) {
        $goutteObject = new Symfony\Component\BrowserKit\Response(
               $guzzleResponse->getBody(true), 
               $guzzleResponse->getStatusCode(), 
               $guzzleResponse->getHeaders()
        );
    
        // Do things with $goutteObject as you normally would.
    }
    

    Note, when you wait for the responses to collect in $guzzleResponses, it will wait for all of the async to complete. If you want to do immediate responses, check out the Guzzle documentation for handling async requests.