2012-07-07 107 views
0

如何使用PHP和Google API在特定網站內搜索?當我搜索關鍵字時,我需要website1.comwebsite2.comwebsite3.com的結果。例如:如何使用PHP和Google API在特定網站中搜索?

<input name="search" value="keyword"> 
<input name="as_site" value="site1.com"> 
<input name="as_site" value="site2.com"> 
<input name="as_site" value="site3.com"> 

結果應該只從這三個網站返回。

回答

1

注意:截至2010年11月1日,Google Web Search API已被正式棄用。它將繼續按照我們的棄用政策進行工作,但您每天可能做出的請求數量將受到限制。因此,我們鼓勵您轉移到新的自定義搜索API。

根據您的表格,並假設關鍵字字段被命名爲keyword此示例代碼假設您只有一個網站進行搜索,您可以自定義它以包括許多。 假設現場輸入名爲site

// The request also includes the userip parameter which provides the end 
// user's IP address. Doing so will help distinguish this legitimate 
// server-side traffic from traffic which doesn't come from an end-user. 
$query = $_POST['keyword']; 
$site = $_POST['site']; 
$url = "https://ajax.googleapis.com/ajax/services/search/web?v=1.0&" 
    . "q={$query}+Site:{$site}&userip=USERS-IP-ADDRESS"; 

// sendRequest 
// note how referer is set manually 
$ch = curl_init(); 
curl_setopt($ch, CURLOPT_URL, $url); 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
curl_setopt($ch, CURLOPT_REFERER, /* Enter the URL of your site here */); 
$body = curl_exec($ch); 
curl_close($ch); 

// now, process the JSON string 
$json = json_decode($body); 
// now have some fun with the results... 
相關問題