2014-10-01 96 views
2

我試圖從Google的非官方詞典API中獲得單詞的同義詞,但我無法弄清楚如何選擇我想要的數據。這是我使用的網址:從谷歌的非官方詞典API中獲取數據

$url = 'https://www.googleapis.com/scribe/v1/research?key=AIzaSyDqVYORLCUXxSv7zneerIgC2UYMnxvPeqQ&dataset=dictionary&dictionaryLanguage=en&query=hello' 

那麼我這樣做:

$data = file_get_contents($url); 
echo $data; 

一切正常返回,但作爲一個字符串,所以我不能弄清楚如何同義詞隔離。我試過simplexml_load_file($url);,但我無法獲得任何迴應/打印。

回答

2

這是你想要的代碼:

<?php 
function object_to_array($data) 
{ 
    if (is_array($data) || is_object($data)) 
    { 
     $result = array(); 
     foreach ($data as $key => $value) 
     { 
      $result[$key] = object_to_array($value); 
     } 
     return $result; 
    } 
    return $data; 
} 

function getSynonims($word) 
{ 
    $url = 'https://www.googleapis.com/scribe/v1/research?key=AIzaSyDqVYORLCUXxSv7zneerIgC2UYMnxvPeqQ&dataset=dictionary&dictionaryLanguage=en&query='.$word; 
    $ret = null; 
    $data = file_get_contents($url); 
    $data = object_to_array(json_decode($data)); 
    if (isset($data['data'][0]['dictionary']['definitionData']['0']['meanings'][0]['synonyms'])) 
     $synonyms = $data['data'][0]['dictionary']['definitionData']['0']['meanings'][0]['synonyms']; 
    foreach ($synonyms as $key => $synonym) { 
     $ret[$key] = $synonym['nym']; 
    } 
    return $ret; 
} 

例如

$word = 'house'; 
print_r(getSynonims($word)); 

輸出

Array 
(
    [0] => residence 
    [1] => home 
    [2] => place of residence 
) 

有用

1

它是JSON,所以對其進行分析,如:

$data = json_decode($url); 

See PHP docs on json_decode

此外,您可以使用這個超級有用的工具jsonlint.com來檢查該字符串是否會解析爲正確的JSON。