我正在研究使用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个结果。现在,我打算通过循环在一个结果页面(不是分开的10页)中获取100个结果。我补充说:
$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;
}
}
}
&GT;
但它没有像它那样有效。我在这里尝试了一些提示:PHP How can I open several sources using curl? 但它没有奏效,:( 有人可以帮我解决这个问题吗?感谢..
答案 0 :(得分: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;
}
}