user2881954
user2881954

Reputation: 157

Google API JSON Postal Code with PHP in Address Object

I want go get the adress details from a JSON return like:

http://maps.googleapis.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&sensor=false

But the Array always differs in the amount of elements. So any Idea how to get the adress details like postal code with php?

Upvotes: 3

Views: 2659

Answers (2)

Marek Sapiński
Marek Sapiński

Reputation: 138

Just a little addition to the answer provided by Springie. If you want to loop through the whole array, you'll need to add another condition, because you might end up with getting only prefix of the post code.

if ( isset($address_components->types) 
    && $address_components->types[0] === 'postal_code'
    && !in_array('postal_code_prefix', $address_components->types) ) { }

Upvotes: 0

Springie
Springie

Reputation: 728

This should work for you if you want to retrieve the postal_code. It should give you the idea of how to access the other data you require:

// Decode json
$decoded_json = json_decode($json);

foreach($decoded_json->results as $results)
{

    foreach($results->address_components as $address_components)
    {
        // Check types is set then get first element (may want to loop through this to be safe,
        // rather than getting the first element all the time)
        if(isset($address_components->types) && $address_components->types[0] == 'postal_code')
        {
                    // Do what you want with data here
            echo $address_components->long_name;            
        }
    }
}

Upvotes: 5

Related Questions