2012-10-07 27 views
0

我正在嘗試構建網站,用戶可以在其中輸入他的網站並在Google中檢查其索引頁面。 就像我們通過site:domain.com使用Google API進行域索引檢查

我使用的是谷歌的API做的,這裏是鏈接到API(我知道這是不建議使用)

http://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=

當我使用像

<?php 

function getGoogleCount($domain) { 
    $content = file_get_contents('http://ajax.googleapis.com/ajax/services/' . 
     'search/web?v=1.0&filter=0&q=site:' . urlencode($domain)); 
    $data = json_decode($content); 
    return ($data->responseData->cursor->estimatedResultCount); 
} 

echo getGoogleCount('stackoverflow.com'); 

?> 
代碼

好,據我想知道的結果計數 但我想要的下一件事是列出我的網站上的所有結果。我不能搶的結果,因爲當我們寫

$data->responseData->cursor->estimatedResultCount 

它直接 但是,當我們試圖得到結果。我不知道該怎麼做,只是爲了打印想法

$data->responseData->results->[url & title & content here] 

因爲這裏的結果是一個數組。我不知道在這種情況下我怎麼能將信息存儲在數組中。

一直在尋找了很久卻找不到任何有關.....提前

謝謝...

回答

1

最簡單的方法是使用:

$data = json_decode($content, true); 

這會將對象轉換爲可能更容易處理的常規關聯數組。 然後你的東西訪問您的價值觀是這樣的:

$results = $data['responseData']['results']; //array 
$googleCount = $data['responseData']['cursor']['estimatedResultCount']; 

然後的結果,你可以做這樣的事情:

foreach ($results as $result) { 
    echo $result['title'].' -> '.$result['url'] . '<br />'; 
} 

不過,當然,如果你不喜歡關聯數組和你喜歡對象,你可以做到這一點也這樣說:

$data = json_decode($content); 
foreach ($data->responseData->results as $result) { 
    echo $result->title .' -> '.$result->url.'<br />'; 
} 

如果你想檢查哪些屬性有$結果,只是使用print_rvar_dump

+0

謝謝,但我無法理解你說 '$ results = $ data ['responseData'] ['results']; // array' 我的意思是它將以哪種形式存儲數據?我無法用這個原因'echo'這個數組 – Leo

+0

'致命錯誤:不能在第7行使用類型爲stdClass的對象作爲/home/upocketm/public_html/www.funfeat.com/clients/api/check.php中的數組'第7行說'\t $ googleCount = $ data ['responseData'] ['cursor'] ['estimatedResultCount'];'這是否有意義? – Leo

+0

你不能回顯數組。您可以使用'print_r'來查看存儲在其中的內容,然後像示例中所示的那樣通過鍵訪問值。你會得到這個致命的錯誤,因爲你沒有將'true'作爲第二個參數傳遞給函數'json_decode'。請仔細檢查我的例子。 –