【问题标题】:PHP Select XML Attribute in Object in Array in an Array of an Object NestedPHP在嵌套对象的数组中选择数组中的对象中的XML属性
【发布时间】:2017-06-26 17:10:48
【问题描述】:

我在抓取和迭代一些有点隐藏的 XML 数据时遇到了麻烦。我可以将对象获取到print_r,但不仅仅是单个属性值。

这是简化的 XML。巢是准确的。

SimpleXMLElement Object ( 
    [@attributes] => Array ( 
    [amenity] => Array ( 
        [0] => SimpleXMLElement Object ( 
            [@attributes] => Array ( 
                [distance] => Within Facility 
                [name] => Biking 
            ) 
        ) 
        [1] => SimpleXMLElement Object ( 
            [@attributes] => Array ( 
                [distance] => Within Facility 
                [name] => Bird Watching 
            )
        )
...
)
)
)

我想获取/呼应每个便利设施的名称。

$amenitiesSet = $xml->amenity;

foreach ($amenitiesSet as $am) {
    print_r($am[0]);    
}

抓取每个对象。每一次深入的尝试都失败了。我知道我缺少一些简单的东西。我不确定何时使用[i]['string']-> 等。我是使用 XML 数据集的新手。

类似$am[0]->name

【问题讨论】:

    标签: php arrays xml loops object


    【解决方案1】:

    好的,所以我终于想出了一个解决方案。这样做的技巧是遍历对象数组中的对象,然后将对象属性更改为字符串。然后我可以建立列表。这是最终的循环代码。

    foreach($xml->amenity as $AMN){
                $amNameItem = (string)$AMN['name'];
                $amList .= $amNameItem.', ';
            }
    

    不知道这是否是最好的解决方案,但至少我可以从 xml 对象数组中的对象数组中获取对象属性列表。

    【讨论】:

      猜你喜欢
      • 2018-07-02
      • 1970-01-01
      • 2021-10-29
      • 1970-01-01
      • 2020-11-03
      • 2015-05-04
      • 1970-01-01
      • 2016-11-25
      • 2021-10-27
      相关资源
      最近更新 更多