Created
January 11, 2016 16:35
-
-
Save volkan/be522078c9b8d23e858b to your computer and use it in GitHub Desktop.
Match a result to a request when sending multiple requests. ref 1: http://stackoverflow.com/questions/22649888/how-to-match-a-result-to-a-request-when-sending-multiple-requests
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
use GuzzleHttp\Event\CompleteEvent; | |
use GuzzleHttp\Event\ErrorEvent; | |
use GuzzleHttp\Client; | |
use GuzzleHttp\Pool; | |
$urls = ['http://www.google.com', 'http://www.facebook.com'] | |
$client = new Client([ | |
'verify' => false, | |
]); | |
$allResults = []; | |
$requests = []; | |
foreach ($urls as $url) { | |
$requests[] = $client->createRequest('GET', $url, [ | |
'verify' => false, | |
'headers' => ['User-Agent' => 'Mozilla/5.0'], | |
'events' => [ | |
'complete' => function (CompleteEvent $e) use (&$allResults, $url){ | |
$response = $e->getResponse(); | |
$allResults[$url] = $response; | |
}, | |
'error' => function (ErrorEvent $e) use (&$allResults, $url){ | |
$exception = $e->getException(); | |
$allResults[$url] = $exception; | |
} | |
] | |
]); | |
} | |
// Results is a GuzzleHttp\BatchResults object. | |
$results = Pool::batch($client, $requests); | |
/** @var \GuzzleHttp\Message\ResponseInterface $response */ | |
if (isset($allResults[$url]) && ($response = $allResults[$url]) && ($response instanceof \GuzzleHttp\Message\ResponseInterface)) { | |
$content = $response->getBody(); | |
} elseif ($response instanceof \GuzzleHttp\Exception\ConnectException) { | |
/** @var \GuzzleHttp\Exception\ConnectException $response */ | |
$exceptionMessage = $response->getMessage(); | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment