gpt4 book ai didi

php - 动态访问嵌套对象

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:42:32 25 4
gpt4 key购买 nike

我正在构建一个可以利用多个网络服务进行地理编码(即 Google、Yahoo、Bing 等)的地理编码类。我正在尝试以一种可以轻松配置新 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 特定代码破坏我的地理编码方法。

谢谢!

最佳答案

当你做的时候

$xml->{$lat_path};

PHP 将使用 $lat_path 中的任何内容作为变量名。它不会进入对象图或完全服从T_OBJECT_OPERATOR。它只会寻找一个属性

 'result[0]->geometry->location->lat;'

$xml 中。尝试运行此代码作为示例:

$obj = new StdClass;
$obj->{'result[0]->geometry->location->lat;'} = 1;
print_r($obj);

会输出

stdClass Object
(
[result[0]->geometry->location->lat;] => 1
)

如您所见,它是一个单一属性,而不是嵌套对象图。

如评论中建议的那样,使用 XPath 或直接转到所需的值:

$xml->result[0]->geometry->location->lat;

关于php - 动态访问嵌套对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7037240/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com