Reputation: 33
I am trying to decode the Google Dictionary API JSON response with PHP, but I am running into an issue where I cannot seem to parse the response (json_decode
returns NULL
).
An example JSON response is located here (searching for the word "oracle").
The JSON API requires that you submit a callback function, so I chose something really short (a
), since it's unnecessary to deal with.
Here is my code:
<?php
$query = 'oracle';
$file = file_get_contents('http://www.google.com/dictionary/json?callback=a&q='.$query.'&sl=en&tl=en&restrict=pr,de&client=te');
var_dump($file);
$json = json_decode($file);
var_dump($json);
?>
Upvotes: 3
Views: 3725
Reputation: 2156
Google returns the result in the form of a function call. If you want to get rid of that you can do: So you have to strip that part off:
$file = substr($file, 2, -10);
Furthermore all the hex characters cause a mess. I don't know the best way of dealing with these (they should be converted to their character, but how to go about that easily requires thought). For testing purposes you can just strip them (to see that it then works). Try:
$file = preg_replace("/\\\x[0-9a-f]{2}/", "", $file);
So in the end you have:
<?php
$query = 'oracle';
$file = file_get_contents('http://www.google.com/dictionary/json?callback=a&q='.$query.'&sl=en&tl=en&restrict=pr,de&client=te');
// var_dump($file);
$file = substr($file, 2, -10);
$file = preg_replace("/\\\x[0-9a-f]{2}/", "", $file);
echo $file;
$json = json_decode($file);
var_dump($json);
?>
For converting the characters as needed, I suppose you could use preg_replace_callback, but I don't like that function, specially when the data comes from a remote source. Simpler may be to simply have a static mapping, eg:
$from = array("\x3d", "\x22", ...);
$to = array("=", "\"", ...);
$file = str_replace($from, $to, $file);
Upvotes: 5