【发布时间】:2011-10-25 14:52:12
【问题描述】:
我正在构建一个地理编码类,它可以利用多种网络服务进行地理编码(即 Google、Yahoo、Bing 等)。我正在尝试以一种可以轻松配置新 Web 服务的方式来实现它。大多数 Web 服务返回 XML/JSON.. 对于 PHP,我选择 XML 作为我的主要关注点。所有代码都已经到位,但现在 Google 例如返回以下 XML(转换为 simple_xml_element)
SimpleXMLElement Object
(
[status] => OK
[result] => Array
(
[0] => SimpleXMLElement Object
(
[type] => postal_code
[formatted_address] => 1010 Lausanne, Switzerland
[address_component] => Array
(
[0] => SimpleXMLElement Object
(
[long_name] => 1010
[short_name] => 1010
[type] => postal_code
)
[1] => SimpleXMLElement Object
(
[long_name] => Lausanne
[short_name] => Lausanne
[type] => Array
(
[0] => locality
[1] => political
)
)
[2] => SimpleXMLElement Object
(
[long_name] => Vaud
[short_name] => VD
[type] => Array
(
[0] => administrative_area_level_1
[1] => political
)
)
[3] => SimpleXMLElement Object
(
[long_name] => Switzerland
[short_name] => CH
[type] => Array
(
[0] => country
[1] => political
)
)
)
[geometry] => SimpleXMLElement Object
(
[location] => SimpleXMLElement Object
(
[lat] => 46.5376186
[lng] => 6.6539665
)
[location_type] => APPROXIMATE
[viewport] => SimpleXMLElement Object
(
[southwest] => SimpleXMLElement Object
(
[lat] => 46.5253574
[lng] => 6.6384420
)
[northeast] => SimpleXMLElement Object
(
[lat] => 46.5467887
[lng] => 6.6745222
)
)
[bounds] => SimpleXMLElement Object
(
[southwest] => SimpleXMLElement Object
(
[lat] => 46.5253574
[lng] => 6.6384420
)
[northeast] => SimpleXMLElement Object
(
[lat] => 46.5467887
[lng] => 6.6745222
)
)
)
)
)
我需要的信息在 [location] 标签中,所以我尝试将路径存储在 var 中:
$lat_path = 'result[0]->geometry->location->lat;
然后尝试以这种方式访问该值:
(suppose $xml is the object)
$xml->{$lat_path};
但这不起作用。有什么方法可以动态或基于变量访问信息。我不想用 Google 特定的代码破坏我的地理编码方法。
谢谢!
【问题讨论】:
-
使用 SimpleXMLElement::xpath 代替 php 反对表示法。 (如果你能展示一些xml,我会尝试提供一个示例实现)
-
你可以为此编写方法然后忘记..
-
我也尝试过使用 Xpath,但它不起作用:( print_r($xml->Xpath('geometry/location')); 给了我一个空数组。
标签: php xml web-services google-maps