0

我正在尝试使用搜索 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);


}
?>

任何输入表示赞赏。

4

1 回答 1

2

行。只需尝试以下代码:

<?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>';
        }
    }

}
?>
于 2013-07-21T14:34:49.493 回答