无法使用谷歌搜索API
<?php
session_start();
require_once('JSON.php');
$url= 'http://ajax.googleapis.com/ajax/services/search/web?rsz=large&v=1.0&q='. $_POST['searchquery'].'&key=ABQIAAAA4oH5MwaexHdhZg4UWRNB1RT2yXp_ZAY8_ufC3CFXhHIE1NvwkxTzUf4N43torAasiY6JD5CaJS6n7Q&userip=http://localhost/';
echo $url;
// use fopen and fread to pull Google's search results
$handle = fopen($url, 'rb');
$body = '';
while (!feof($handle)) {
$body .= fread($handle, 8192);
echo $body;
}
fclose($handle);
// now $body is the JSON encoded results. We need to decode them.
$json = new Services_JSON();
$json = $json->decode($body);
var_dump($json);
}
?>
当我尝试运行此脚本时,出现错误 [function.fopen]: 无法打开流: HTTP 请求失败!
如果我获取生成的 $url 并将其粘贴到地址栏中,我会得到所需的响应。
谁能帮忙并让我知道如何解决这个问题。谢谢
<?php
session_start();
require_once('JSON.php');
$url= 'http://ajax.googleapis.com/ajax/services/search/web?rsz=large&v=1.0&q='. $_POST['searchquery'].'&key=ABQIAAAA4oH5MwaexHdhZg4UWRNB1RT2yXp_ZAY8_ufC3CFXhHIE1NvwkxTzUf4N43torAasiY6JD5CaJS6n7Q&userip=http://localhost/';
echo $url;
// use fopen and fread to pull Google's search results
$handle = fopen($url, 'rb');
$body = '';
while (!feof($handle)) {
$body .= fread($handle, 8192);
echo $body;
}
fclose($handle);
// now $body is the JSON encoded results. We need to decode them.
$json = new Services_JSON();
$json = $json->decode($body);
var_dump($json);
}
?>
When i try to run this script i get error [function.fopen]: failed to open stream: HTTP request failed!
if i take the $url that is generated and paste it in address bar i get the required response.
Can anyone help and let me know how i can resolve this problem. Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
而不是上面的代码,请尝试:
$url= 'http://ajax.googleapis.com/ajax/services/search/web?rsz=large&v=1.0&q='。 $_POST['searchquery'].'&key=ABQIAAAA4oH5MwaexHdhZg4UWRNB1RT2yXp_ZAY8_ufC3CFXhHIE1NvwkxTzUf4N43torAasiY6JD5CaJS6n7Q&userip=http://localhost/';
$json = file_get_contents($url);
$myArr = json_decode($json);
var_dump($myArr);
我不确定,但如果 searchquery 中有空格,您可能需要将 $_POST['searchquery'] 替换为 urlencode($_POST['searchquery']) 。
来自:如何检索&在 PHP 中使用网站的 JSON 响应?
instead of your code above, try:
$url= 'http://ajax.googleapis.com/ajax/services/search/web?rsz=large&v=1.0&q='. $_POST['searchquery'].'&key=ABQIAAAA4oH5MwaexHdhZg4UWRNB1RT2yXp_ZAY8_ufC3CFXhHIE1NvwkxTzUf4N43torAasiY6JD5CaJS6n7Q&userip=http://localhost/';
$json = file_get_contents($url);
$myArr = json_decode($json);
var_dump($myArr);
i am not sure, but maybe you need to replace $_POST['searchquery'] with urlencode($_POST['searchquery']) for cases if there are spaces in the searchquery.
from: How to retrieve & use the JSON response of website in PHP?