bo-*_*-oz 5 php xml google-maps web-services
我正在构建一个Geocoding类,它可以利用多个Web服务进行地理编码(即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
)
)
)
)
)
Run Code Online (Sandbox Code Playgroud)
我需要的信息是在[location]标签中,所以我尝试将路径存储在var中:
$lat_path = 'result[0]->geometry->location->lat;
Run Code Online (Sandbox Code Playgroud)
然后尝试以这种方式访问该值:
(suppose $xml is the object)
$xml->{$lat_path};
Run Code Online (Sandbox Code Playgroud)
但这不起作用.有什么方法可以动态或基于变量访问信息.我不想破坏我使用Google特定代码的Geocoding方法.
谢谢!
当你这样做时
$xml->{$lat_path};
Run Code Online (Sandbox Code Playgroud)
PHP 将使用其中的任何内容$lat_path作为变量名。它不会进入对象图或T_OBJECT_OPERATOR根本不遵守。它只会寻找一个属性
'result[0]->geometry->location->lat;'
Run Code Online (Sandbox Code Playgroud)
在$xml。尝试运行此代码作为示例:
$obj = new StdClass;
$obj->{'result[0]->geometry->location->lat;'} = 1;
print_r($obj);
Run Code Online (Sandbox Code Playgroud)
它将输出
stdClass Object
(
[result[0]->geometry->location->lat;] => 1
)
Run Code Online (Sandbox Code Playgroud)
正如您所看到的,它是一个单一属性,而不是嵌套对象图。
就像评论中建议的那样,要么使用 XPath 要么直接转到所需的值:
$xml->result[0]->geometry->location->lat;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2486 次 |
| 最近记录: |