2010-11-10 124 views
0
<?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請求失敗!無法使用谷歌搜索api

如果我把$ url生成並粘貼到地址欄中,我會得到所需的響應。

任何人都可以幫助,讓我知道我可以如何解決這個問題。由於

回答

0

,而不是你上面的代碼,請嘗試:

$ 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中有空格,可能需要用urlencode($ _ POST ['searchquery'])替換$ _POST ['searchquery']。

來自:How to retrieve & use the JSON response of website in PHP?

+0

謝謝...謝謝謝謝......你的天才:)這是一件很簡單但我一直缺少it..thanks百萬 – shaz 2010-11-10 07:14:40