如何发送多个请求并将结果与​​每个请求匹配

时间:2019-09-10 07:10:18

标签: php guzzle guzzle6 guzzlehttp

我正在使用guzzle发送多个请求以获取多个网站的标题和网站图标。我有一个问题。首先是我如何匹配每个请求(网站)的结果。我需要显示网址以及标题和favcion。另外,这需要很多时间。我的代码有什么问题吗?这是我的代码:

public function getContent()
    {
        $links = array("https://www.google.com/","https://www.google.com/","https://www.google.com/");
        $promises = array();
        foreach ($links as $link) {
            $client = new Client([
                'Content-Type' => 'application/json',
            ]);
            $promise = $client->getAsync($link)
            ->then(function ($response) {

            return $response->getBody()->getContents();

            });
            //$promises['website'] = "abcd";    
            $promises[] = $promise->wait();

        }
       $result = $this->getData($promises);
       return $result;

private function getData($all_data)
    {
        $params = [];
        foreach($all_data as $data){
            $crawler = new Crawler($data['data']);
            $title = $crawler->filter('title');
            if($crawler->filter('title')->count() > 0 ){
                $get_title = $crawler->filter('title')->text();
            }
            else{
                $get_title = null;
            }
            $icon = $crawler->filter("link[rel = 'shortcut icon']");
            if($crawler->filter("link[rel = 'shortcut icon']")->count() > 0){
                $get_icon = $crawler->filter("link[rel = 'shortcut icon']")->attr('href');
            }
            else{
                $get_icon = null;
            }
            $params[] = array('title'=>$get_title, 'icon'=>$get_icon);
        }
        return $params;
    }

0 个答案:

没有答案