语法问题:访问PHP对象

时间:2011-06-17 20:52:24

标签: php object syntax

我有一个从$ xml = simplexml_load_file($ file)返回的对象。我正在尝试访问“location-id”和“item-id”,但我无法弄清楚如何访问这些信息。如果它只嵌套一次,我知道我可以做一些像$ xml-> {'item-id'}但它似乎不起作用。这是什么语法?很抱歉没有格式化..这就是我在浏览器上的返回方式。

SimpleXMLElement Object (
    [item] => Array (
        [0] => SimpleXMLElement Object (
            [@attributes] => Array (
                [item-id] => AAA )
            [locations] => SimpleXMLElement Object (
                [location] => SimpleXMLElement Object (
                    [@attributes] => Array (
                        [location-id] => 111
                    )
                    [quantity] => 1
                    [pick-up-now-eligible] => false
                )
            )
        )
        [1] => SimpleXMLElement Object
            [@attributes] => Array (
                [item-id] => BBB
            )
            [locations] => SimpleXMLElement Object (
                [location] => SimpleXMLElement Object (
                    [@attributes] => Array (
                        [location-id] => 111
                    )
                    [quantity] => 1
                    [pick-up-now-eligible] => false
                )
            )
        )
    )
) 

有人可以插话吗? TIA !!

2 个答案:

答案 0 :(得分:2)

它是

$xml->item[0]->attributes('item-id');
$xml->item[0]->locations->location->attributes('item-id');

答案 1 :(得分:1)

要访问SimpleXML中的属性,可以使用数组样式语法。

$element['attribute_name'];

SimpleXMLElement::attributes()方法也可用。以上将是:

$element->attributes()->attribute_name;

如果属性是命名空间(例如blah:attribute_name),那么您可以将该命名空间(作为前缀或URI)提供给attributes()方法。

$element->attributes('blah', TRUE)->attribute_name;
$element->attributes('http://example.org/blah')->attribute_name;

有关详细信息,请参阅SimpleXML Basic Usage手册页。


要将上述内容付诸实践,要打印第二个item-id元素的<item>属性,您可以使用:

echo $xml->item[1]['item-id'];

以下示例循环遍历<item>元素并打印其关联的item-id和(第一个)location-id值。

foreach ($xml->item as $item) {
    $location = $item->locations->location;
    echo 'Item ID: ' . $item['item-id'] . "\n";
    echo 'Locations: ' . $location['location-id'] . "\n";
}