0

我正在研究使用 Google CSE 的项目。在这一步,我正在编写代码以从中检索 JSON 结果。这是代码:

<?php
function cURL($url, $ref, $p) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
curl_setopt($ch, CURLOPT_REFERER, $ref);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
if ($p) {
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $p);
}
$result = curl_exec($ch);
curl_close($ch);
if ($result) {
    return $result;
} else {
    return '';
}
}

if (isset($_GET['keyword'])) {
$keyword = $_GET['keyword'];
} else {
echo 'salah bro!';
}
$cseNumber = 'aaa'; // Key for the API thing
$key = 'bbb'; //Key for Nofriani's account: sorta a password
$start = '1';
$file = cURL('https://www.googleapis.com/customsearch/v1?key=' . $key . '&cx=' . $cseNumber . '&q=' . $keyword . '&siteSearchFilter=i&alt=json&start=' . $start, 'https://www.googleapis.com/customsearch/v1?key=' . $key . '&cx=' . $cseNumber . '&q=' . $keyword . '&siteSearchFilter=i&alt=json&start=' . $start, null);
echo $file;

?>

它运行良好,我得到了 10 个 Google CSE 的第一个结果。不幸的是,API 限制只能批量检索 10 个结果。现在,我打算通过循环将 100 个结果放入一个结果页面(而不是单独的 10 个页面)。我添加了这个:

$start= '';
$file = cURL('https://www.googleapis.com/customsearch/v1?key=' . $key . '&cx=' . $cseNumber . '&q=' . $keyword . '&siteSearchFilter=i&alt=json&start=' . $start, 'https://www.googleapis.com/customsearch/v1?key=' . $key . '&cx=' . $cseNumber . '&q=' . $keyword . '&siteSearchFilter=i&alt=json&start=' . $start, null, $start);
return $file;

function getResult() {
    for ($i = 0; $i <= 90; $i+=10) {
        $file .= cURL($url, $ref, $p, ($i + 1));
        for ($j = 0; $j < 10; $j++) {
            echo $file;
        }
    }
}

?>

但它并没有像以前那样工作。我在这里尝试了一些技巧:PHP How can I open multiple sources using curl? 但它没有那么好,:(谁能帮我解决这个问题?谢谢..

4

1 回答 1

0

你忘记了很多东西,比如参数和连接。正确的功能将是这样的

更新

function getResult($key,$cseNumber,$keyword) { // parameter added
    for ($i = 1; $i <= 10; $i++) {
        $file = cURL('https://www.googleapis.com/customsearch/v1?key=' . $key . '&cx=' . $cseNumber . '&q=' . $keyword . '&siteSearchFilter=i&alt=json&start=' . $i, 'https://www.googleapis.com/customsearch/v1?key=' . $key . '&cx=' . $cseNumber . '&q=' . $keyword . '&siteSearchFilter=i&alt=json&start=' . $i, null); // . removed from here
        echo $file;
    }
}
于 2013-05-17T04:16:47.237 回答