unable to use google search 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);
}
?>
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
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?
精彩评论