如何使用 GuzzleHttp 發出非同步的 HTTP 請求?

在 GuzzleHttp 中允許你使用 Pool 的方式發送非同步 HTTP 請求,這邊是一個範例讓你可以發送請求後將回傳資料存成 HTML

$requests = [
    new Request('GET', '/'),
    new Request('GET', '/%e5%a6%82%e4%bd%95%e5%9c%a8-mailgun-%e4%b8%ad%e8%a8%ad%e5%ae%9a%e7%99%bc%e9%80%81%e7%94%a8%e7%9a%84-smtp-%e4%bf%a1%e7%ae%b1%ef%bc%9f/'),
    new Request('GET', '/wordpress%e5%af%a6%e4%bd%9c%ef%bc%8d%e7%b6%b2%e7%ab%99%e7%99%bd%e7%9a%ae%e6%9b%b8%ef%bd%9c%e6%96%b0%e5%bb%ba%e8%a1%a8%e5%96%ae%ef%bd%9c%e5%9b%9e%e5%82%b3pdf%e6%aa%94%e6%a1%88/'),
    new Request('GET', '/wp-console-%e8%a6%81%e6%80%8e%e9%ba%bc%e4%bd%bf%e7%94%a8-%e5%b9%ab%e4%bd%a0%e6%89%be%e5%88%b0%e7%ae%a1%e7%90%86wp%e7%9a%84%e6%96%b0%e6%96%b9%e6%b3%95/'),
    new Request('GET', '/tappay%e9%87%91%e6%b5%81%e4%b8%b2%e6%8e%a5/')
];

$client = new Client(['base_uri' => 'https://inbound.technology/']);

$pool = new Pool($client, $requests, [
    'fulfilled' => function (Response $response, $index) {
        Logger::log('fulfilled ' . $index);
        file_put_contents($index . '.html', $response->getBody());
    },
    'rejected' => function (RequestException $reason, $index) {
        Logger::log('rejected ' . $index);
    },
]);

$promise = $pool->promise();

$promise->wait();