2012-02-08 46 views
5

總之,我正在尋找一種方式來做到這一點:將Google搜索結果讀入PHP數組?

$results_array = google("search terms"); // returns array of URLs 

因此,舉例來說,如果我的搜索詞是「貓視頻」我的$ results_array [0]可能是YouTube網址,並$ results_array 1可能在Vimeo上。

我見過Google Custom Search API,但它們都需要複雜的JSON轉換,ATOM,REST或其他一些對我所要做的事情過於複雜的系統。

有沒有簡單的解決方案呢?

編輯:我找到了,感謝另一個帖子

感謝this post我能弄明白。總之,我只是用了以下內容:

$results = json_decode(file_get_contents( 
      'http://ajax.googleapis.com/ajax/services/search/web?v=1.0&q='. 
      urlencode($search))); 

echo $results->responseData->results[$resultNumber]->url; 

我有點驚訝,由downvotes disapointed - 這似乎是一個相當普遍的問題,事實上,一個非常簡單的答案。這確實涉及JSON,但對用戶完全透明。也許更準確的解決方案,我問的是:

function google($query) { 
    $results = json_decode(file_get_contents( 
      'http://ajax.googleapis.com/ajax/services/search/web?v=1.0&q='. 
      urlencode($search))); 

    return $results->responseData->results 
} 
+4

JSON如何過於複雜?看起來像是您實施的首選。絕對不像解析HTML搜索結果那麼複雜... – 2012-02-08 18:00:30

+2

谷歌不喜歡任何試圖繞過它們的API,所以如果你嘗試直接請求並解析結果 - 你的主機可能被禁止。 – Cheery 2012-02-08 18:01:36

回答

3

如果你要獲得視頻結果,那麼你可以試試這個。

//replace space between words with + 
$query = "cat+video"; 
$start = 0; 
/* 
this url will give you json response with 4 results each time. 
u have to change the $start like 0, 4, 8,... 
use json_decode() and get it in array 
*/ 

$url = 'https://ajax.googleapis.com/ajax/services/search/video?v=1.0&q='.$query.'&start='.$start 

希望這會對您有所幫助。