I’m playing with Google Maps and Geocoding (converting Address to lang/lat coordinates). Everything works fine so far and I’m getting an answer from the google maps server with a file:
$address = urlencode( $address );
$url = "http://maps.google.com/maps/api/geocode/json?address={$address}&sensor=false";
$content = file_get_contents( $url );
echo '<pre>';
print_r( $content );
echo '</pre>';
Point is that I don’t need all that information.
Questions
A How do I get only a part of the JSON object?
(Example: I only need 'results'->'address_components'->'type' = 'country';.)
B Can I reduce the content of the returned (google) file somehow as I don’t need everything?
Update
I need to add part of the data to a json object. So decoding & then encoding seems like a loss of energy & time (at this point). Any ideas if I’d be better (faster) off with requesting a XML object? (The final set of objects is pretty large. This is why I should really care about performance.)
Example JSON answer from Google Maps maps server (file content):
{
"results" : [
{
"address_components" : [
{
"long_name" : "28",
"short_name" : "28",
"types" : [ "street_number" ]
},
{
"long_name" : "Sellhorner Weg",
"short_name" : "Sellhorner Weg",
"types" : [ "route" ]
},
{
"long_name" : "Behringen",
"short_name" : "Behringen",
"types" : [ "sublocality", "political" ]
},
{
"long_name" : "Bispingen",
"short_name" : "Bispingen",
"types" : [ "locality", "political" ]
},
{
"long_name" : "Soltau-Fallingbostel",
"short_name" : "Soltau-Fallingbostel",
"types" : [ "administrative_area_level_2", "political" ]
},
{
"long_name" : "Niedersachsen",
"short_name" : "NDS",
"types" : [ "administrative_area_level_1", "political" ]
},
{
"long_name" : "Deutschland",
"short_name" : "DE",
"types" : [ "country", "political" ]
},
{
"long_name" : "29646",
"short_name" : "29646",
"types" : [ "postal_code" ]
}
],
"formatted_address" : "Sellhorner Weg 28, 29646 Bispingen, Deutschland",
"geometry" : {
"location" : {
"lat" : 53.118080,
"lng" : 9.966859999999999
},
"location_type" : "ROOFTOP",
"viewport" : {
"northeast" : {
"lat" : 53.11942898029150,
"lng" : 9.96820898029150
},
"southwest" : {
"lat" : 53.11673101970850,
"lng" : 9.965511019708496
}
}
},
"partial_match" : true,
"types" : [ "street_address" ]
}
],
"status" : "OK"
}
Gives you all
address_componentswhich have a type'country'. Probably that’s only going to be one, but it may be more than one. This syntax requires PHP 5.3+ BTW.Just take the parts of the decoded
$arrayyou need and forget the rest. If you want,json_encodeit again.