2016-09-16 72 views
0
$query = "Poultry meat is a major source of animal protein considering"; 

function fetch_google($query) { 
$cleanQuery = str_replace(" ","+",$query); 

$url = 'http://www.google.com/search?q='.urlencode($cleanQuery); 
$data=file_get_contents($url); 
$json = json_decode($data, true); 

for($x=0;$x<count($json->responseData->results);$x++){ 

echo "<b>Result ".($x+1)."</b>"; 
echo "<br>URL: "; 
echo $json->responseData->results[$x]->url; 
echo "<br>VisibleURL: "; 
echo $json->responseData->results[$x]->visibleUrl; 
echo "<br>Title: "; 
echo $json->responseData->results[$x]->title; 
echo "<br>Content: "; 
echo $json->responseData->results[$x]->content; 
echo "<br><br>"; 
} 
    } 

    fetch_google($query); 

我試圖獲得搜索結果,但在返回json_decode給予空值.. 試圖尋找答案,但失敗。谷歌搜索,json_decode給出null

var_dump($url);給出結果..但不是$ JSON

回答

1

您加載的全谷歌搜索結果頁面。 $data中的結果將是頁面返回的完整HTML,而不是json格式的結果。

你需要調用谷歌的API,以便接收一個JSON可以從PHP

可以輕鬆操控檢查的官方文檔here關於谷歌搜索

+0

是否有任何其他方式來獲取不帶API的特定數據? –

+0

如果您從http://www.google.com/search?q=解析HTML結果,則不確定它們的格式是否相同。也許明天谷歌決定改變他們顯示結果的方式。最好的選擇是使用API​​,這是更容易的。 –

+0

好吧..請給出一個示例代碼..不能理解谷歌文檔.. –

0

可能也有解碼原始「時使用此谷歌json的'

$php_json_txt = str_replace('\\x', '\\\\x', $google_json_txt); 
$data = json_decode($php_json_txt, true);