开发者

Syntax question: accessing a PHP object

I have an object returned from $xml = simplexml_load_file($file). I'm trying to access 'location-id' and 'item-id', but I can't figure out how to access those pieces of info. If it only nested once, I know I could do something like $xml->{'item-id'} but it doesn't seem to work. What is the syntax for this? Sorry for the lack of formatting.. that's how it was returned on my browser.

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] => SimpleX开发者_运维百科MLElement Object (
                [location] => SimpleXMLElement Object (
                    [@attributes] => Array (
                        [location-id] => 111
                    )
                    [quantity] => 1
                    [pick-up-now-eligible] => false
                )
            )
        )
    )
) 

Could somebody chime in? TIA!!


it'd be

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


To access attributes in SimpleXML, array-style syntax can be used.

$element['attribute_name'];

The SimpleXMLElement::attributes() method is also available. The above would be:

$element->attributes()->attribute_name;

If the attribute is namespaced (e.g. blah:attribute_name) then you can provide that namespace (as the prefix, or URI) to the attributes() method.

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

See the SimpleXML Basic Usage manual page for further information.


To put the above into practice for this individual question, to print the item-id attribute of the second <item> element, you could use:

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

The example below loops over the <item> elements and prints their associated item-id and (the first) location-id values.

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜