<?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并将其粘贴到地址栏中,我会得到所需的响应。
任何人都可以帮忙,让我知道如何解决这个问题。感谢
答案 0 :(得分:0)
而不是上面的代码,请尝试:
$ url ='http://ajax.googleapis.com/ajax/services/search/web?rsz=large&v=1.0&q='。 $ _POST [ 'SEARCHQUERY'] '&安培;键= ABQIAAAA4oH5MwaexHdhZg4UWRNB1RT2yXp_ZAY8_ufC3CFXhHIE1NvwkxTzUf4N43torAasiY6JD5CaJS6n7Q&安培; USERIP = http://localhost/';
$ json = file_get_contents($ url);
$ myArr = json_decode($ json);
的var_dump($ myArr,该);
我不确定,但是如果searchquery中有空格,则可能需要用urlencode($ _ POST ['searchquery'])替换$ _POST ['searchquery']。
来自:How to retrieve & use the JSON response of website in PHP?