JSON (JavaScript Object Nugget) to PHP array
I am shocked, shocked that Drupal is not already fully buzzword compliant. I expected lots of material on making, sending, getting, reading, and mangling JSON. (I made up the part about the N standing for Nugget by the way. I'm pretty sure it's JavaScript Object something though.)
Instead, Agaric was forced to fall back on the PHP manual: only in PHP 5.2 and above the function json_decode will turn a JSON string into a PHP object (or, optionally, an array).
Which is cool unfortunately the particular JSON I'm getting from Google is much uglier than the CSV version. I just wanted one more piece of data -- the country coded -- but it's wrapped in too much information that you have to know ahead of time to get the simple information you want. (E.g., I don't want to have to know if it's a country to grab the code. If it's there, let me get it, if it's not, that's fine too.)
$q = str_replace(' ', '+', implode(',',$place));
$url = 'http://maps.google.com/maps/geo?q=' . $q . '&output=xml&key=' . variable_get('googlemap_api_key', '');
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$c = curl_exec($ch);
curl_close($ch);
$c = json_decode($c);
drupal_set_message('<pre>' . print_r($c, TRUE) . '</pre>');
stdClass Object
(
[name] => Espana
[Status] => stdClass Object
(
[code] => 200
[request] => geocode
)[Placemark] => Array
(
[0] => stdClass Object
(
[id] => p1
[address] => Spain
[AddressDetails] => stdClass Object
(
[Country] => stdClass Object
(
[CountryNameCode] => ES
)[Accuracy] => 1
)[Point] => stdClass Object
(
[coordinates] => Array
(
[0] => -3.74922
[1] => 40.463667
[2] => 0
))
)
)
)
Let's see if XML is any prettier.
Comments
Here's if you go for a city
Here's if you go for a city instead of a country-- the same way of getting elements still works, and there only ever is a country code:
So this was the old CSV style:
/* csv style
$loc = explode(',', $c);
$lat = $location[2];
$lon = $location[3];
*/
With a little more complication from using JSON, we can get codes for countries also:
$j = json_decode($c);
$ccode = $j->Placemark[0]->AddressDetails->Country->CountryNameCode;
$lat = $j->Placemark[0]->Point->coordinates[0];
$lon = $j->Placemark[0]->Point->coordinates[1];
JSON = Javascript Object Notation
Notation, not nugget. See http://json.org/
Also, json_decode($decode_string, TRUE) will return an associative array, so you can do something like the following:
$response = json_decode($c);
if(isset($response['Placemark']) && isset($response['Placemark'][0])) {
$countryCode = $response['Placemark'][0]['AddressDetails']['Country']['CountryNameCode'];
}
Thanks a TON !!
It really worked for me. Much many thanks!!
Post new comment