我正在构建可以利用多个Web服务进行地理编码的Geocoding类(即Google,Yahoo,Bing等)。我试图用这种方式来实现新的web服务可以很容易地配置。大多数Web服务返回XML/JSON ..对于PHP,我选择XML作为我的主要焦点。所有的代码已经到位,但现在谷歌,例如返回以下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
)
)
)
)
)
我需要的信息是在[位置]标签,所以我试图存储路径在VAR:
$lat_path = 'result[0]->geometry->location->lat;
,然后尝试这种方式访问该值:
(suppose $xml is the object)
$xml->{$lat_path};
但这好好尝试的工作。有没有什么办法可以基于动态或变量来访问信息。我不想用Google特定的代码破坏我的地理编码方法。
谢谢!
使用[SimpleXMLElement :: xpath](http://www.php.net/manual/simplexmlelement.xpath.php)代替php异议符号。 (如果你可以显示一些xml,我会尝试提供一个示例实现) – Yoshi
您可以为此编写方法并忘记.. – Vytautas
我也尝试使用Xpath,但它没有工作:( print_r $ xml-> Xpath('geometry/location'));给了我一个空数组。 –