I'm trying to get the synonyms of a word from Google's unofficial dictionary API, but I can't figure out how to select the data I want. This is the URL I'm using:
$url = 'https://www.googleapis.com/scribe/v1/research?key=AIzaSyDqVYORLCUXxSv7zneerIgC2UYMnxvPeqQ&dataset=dictionary&dictionaryLanguage=en&query=hello'
Then I do this:
$data = file_get_contents($url);
echo $data;
Everything is returned correctly, but as a string, so I can't figure out how to isolate the synonyms. I've tried simplexml_load_file($url);
but I can't get anything to echo/print from that.
This is the code you want:
<?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;
}
example:
$word = 'house';
print_r(getSynonims($word));
OUTPUT
Array
(
[0] => residence
[1] => home
[2] => place of residence
)
useful:
It's JSON, so parse it like:
$data = json_decode($url);
Additionally, you can use this super helpful tool jsonlint.com to check if that string will parse to proper JSON.