我创建了一个获取gpslocation的android应用程序并创建了一个url:https://maps.googleapis.com/maps/api/geocode/xml?latlng=00.00,00.00&sensor=true
示例:https://maps.googleapis.com/maps/api/geocode/xml?latlng=42.120636,-72.568731&sensor=true
这返回(只是一部分):
<GeocodeResponse>
<status>OK</status>
<result>
<type>street_address</type>
<formatted_address>
17 Dorchester Street, Springfield, Massachusetts 01109, United States
</formatted_address>
<address_component>
<long_name>17</long_name>
<short_name>17</short_name>
<type> ...
我对这部分感兴趣: 17 Dorchester Street, Springfield, Massachusetts 01109, United States
.
我想创建一个新的网址,其中包含拉链编号"01109",如http://mysite.com?process=01109并打开此网站 .
谁能帮我!
3 回答
因此,您链接到的XML实际上包含邮政编码 . 它是
address_component
,其子项type
的值为postal_code
. 恕我直言,最简单的方法是XPath:要从googleapis地理编码响应中获取特定数据,您不仅需要按名称定位元素,还需要按内容定位元素 .
这可以通过Xpath轻松完成 . 幸运的是,PHP中的SimpleXML扩展支持阅读这种常见的格式化XML文档 .
首先是Xpath:
<result>
元素是具有子<type>
的元素,其节点值为street_address
. 在Xpath中,这表示为:它的工作原理类似于ZIP代码 . 它是前一个
<result>
节点的<address_component>
子节点,其子节点<type>
,节点值为postal_code
,并且是您想要的那个元素:到目前为止,xpaths . 要使其运行,只需加载XML文档,执行路径并读出您感兴趣的值:
通过在您的问题中链接的XML记录,这将创建以下输出:
我希望这是有帮助的 .
您可以使用simplexml和xpath访问postal_code short_name . 这是一个有效的例子:
请注意,必须显式地将值转换为字符串,因为simplexml将在打印时将数组或对象返回到变量而不是字符串(在测试时可能会造成混淆) .