I am trying to get the value inside the <address_component> element that corresponds to <type>postal_code</type> from the XML returned by the Google maps REST API.
For example, in the below:
...
<result>
<type>
route
</type>
<formatted_address>
Rose Ln, Liverpool, Merseyside L18 5ED, UK
</formatted_address>
<address_component>
<long_name>
Rose Ln
</long_name>
<short_name>
Rose Ln
</short_name>
<type>
route
</type>
</address_component>
<address_component>
<long_name>
Liverpool
</long_name>
<short_name>
Liverpool
</short_name>
<type>
locality
</type>
<type>
political
</type>
</address_component>
<address_component>
...
</address_component>
<address_component>
...
</address_component>
<address_component>
<long_name>
L18 5ED
</long_name>
<short_name>
L18 5ED
</short_name>
<type>
postal_code
</type>
</address_component>
<address_component>
...
</address_component>
...
</result>
... more result elements
We see one of the <result> elements. Nested inside are multiple <address_component> elements. Inside one of those is <type>postal_code</type>.
My question is how would I distinguish between these same named elements and choose only the <address_component> with <type>postal_code</type> attributed to it?
If they were uniquely named it would be a simple case of:
foreach ($address_rsponse->result as $address_option) {
$val = $address_option->some_unique_name;
}
However when named the same I am stumped as to a method to pick out an element by it’s child-element.
Could anyone shed any light on the correct approach.
Thanks
You can use XPath with SimpleXML (docs).
The following will give you an array containing the
<address_component>element(s) that you’re looking for.If you want to loop over the
<result>elements, the following will give you an array containing the<address_component>element(s) that you’re looking for and output the first for each<result>.