获得超过10个结果的Google Search API

时间:2013-07-21 14:28:51

标签: php html search-engine google-search-api

我正在尝试使用搜索API从google获取超过10个结果。我知道谷歌搜索API只提供10个结果,你必须调用它10次才能获得100个,但我似乎无法让它工作。我尝试创建一个do while循环以及一个for循环,但它似乎只是一遍又一遍地给我相同的结果。

<?php


if(isset($_GET['input']) && $_GET['input'] != "")
{

    echo "<br />Your Search Results Google:<br /><br />";


    $i=0;



    $url =  "http://ajax.googleapis.com/ajax/services/search/web?v=1.0&    key=AIzaSyBacVRiPNo7uMqhtjXG4Zeq1DtSQA_UOD4&cx=014517126046550339258:qoem7fagpyk
&num=10&start=".$i."&"."q=".str_replace(' ', '%20', $_GET['input'])

// sendRequest
// note how referer is set manually
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_REFERER, 'http://www.google.com');
$body = curl_exec($ch);
    curl_close($ch);





// now, process the JSON string




$json = json_decode($body,true); 


do
{

foreach ($json['responseData']['results'] as $data) {
echo '
    <p>
        ', $data ['title']," ---> <u>Google SE </u>" ,'<br />
        ', '<a href ='.$data['url'].'>'.$data['url']."</a>" , '<br />
        ', $data['content'],'
    </p>';
}

$i++;       

}
while($i<3);


}
?>

任何意见都赞赏。

2 个答案:

答案 0 :(得分:1)

确定。只需尝试下面的代码:

<?php
if(isset($_GET['input']) && $_GET['input'] != "")
{
    echo "<br />Your Search Results Google:<br /><br />";

    for ($i = 0; $i < 10; $i++)
    {

        $url =  "http://ajax.googleapis.com/ajax/services/search/web?v=1.0&key=AIzaSyBacVRiPNo7uMqhtjXG4Zeq1DtSQA_UOD4&cx=014517126046550339258:qoem7fagpyk
            &num=10&start=".$i."&"."q=".str_replace(' ', '%20', $_GET['input']);
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_REFERER, 'http://www.google.com');
        $body = curl_exec($ch);
        curl_close($ch);

        $json = json_decode($body,true);

        foreach ($json['responseData']['results'] as $data) {
            echo '
                <p>
                ', $data ['title']," ---> <u>Google SE </u>" ,'<br />
                ', '<a href ='.$data['url'].'>'.$data['url']."</a>" , '<br />
                ', $data['content'],'
                </p>';
        }
    }

}
?>

答案 1 :(得分:0)

由于现在不推荐使用AJAX Api,您可以使用Serp Api之类的第三方服务来获取Google搜索结果。

应该很容易集成,使用numstart对结果进行分页并获得您想要的100个:

$query = [
    "q" => "Coffee",
    "google_domain" => "google.com",
    "num" => 10,
    "start" => 10,  
];

$serp = new GoogleSearchResults();
$json_results = $serp.json($query);

GitHub存储库。