Php 从谷歌的非官方字典API获取数据
我试图从Google的非官方字典API中获取单词的同义词,但我不知道如何选择所需的数据。这是我正在使用的URL:Php 从谷歌的非官方字典API获取数据,php,Php,我试图从Google的非官方字典API中获取单词的同义词,但我不知道如何选择所需的数据。这是我正在使用的URL: $url = 'https://www.googleapis.com/scribe/v1/research?key=AIzaSyDqVYORLCUXxSv7zneerIgC2UYMnxvPeqQ&dataset=dictionary&dictionaryLanguage=en&query=hello' 然后我会这样做: $data = file_get_co
$url = 'https://www.googleapis.com/scribe/v1/research?key=AIzaSyDqVYORLCUXxSv7zneerIgC2UYMnxvPeqQ&dataset=dictionary&dictionaryLanguage=en&query=hello'
然后我会这样做:
$data = file_get_contents($url);
echo $data;
所有内容都正确返回,但作为字符串返回,因此我不知道如何隔离同义词。我尝试过simplexml\u load\u file$url;但我无法从中获取任何可回送/打印的内容。它是JSON,所以请像以下那样解析它:
$data = json_decode($url);
此外,您可以使用这个超级有用的工具来检查该字符串是否将解析为正确的JSON。这是您想要的代码:
<?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
)