我试图从Google的非官方词典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);
,但我无法从中得到回应/打印。
答案 0 :(得分: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 :(得分:1)