开发者

Choosing Last Node in SimpleXML

开发者 https://www.devze.com 2022-12-17 20:40 出处:网络
I want to find th开发者_C百科e attribute of the last node in the xml file. the following code find\'s the attribute of the first node. Is there a way to find the last node ?

I want to find th开发者_C百科e attribute of the last node in the xml file.

the following code find's the attribute of the first node. Is there a way to find the last node ?

foreach ($xml->gig[0]->attributes() as $Id){
}

thanks


I'm not to familiar with PHP but you could try the following, using an XPath query:

foreach ($xml->xpath("//gig[last()]")[0]->attributes() as $Id){
}


To get to the last gig node, as Frank Bollack noted, we could use XPath.

foreach (current($xml->xpath('/*/gig[last()]'))->attributes() as $attr) {
}

Or a little more verbose but nicer:

$attrs = array();
$nodes = $xml->xpath('/*/gig[last()]');
if (is_array($nodes) && ! empty($nodes)) {
    foreach ($nodes[0]->attributes() as $attr) {
        $attrs[$attr->getName()] = (string) $attr;
    }
}
var_dump($attrs);


It's true that you could use XPath to get the last node (be it a <gig/> node or otherwise) but you can also mirror the same technique you used for the first node. This way:

// first <gig/>
$xml->gig[0]

// last <gig/>
$xml->gig[count($xml->gig) - 1]

Edit: I've just realized, are you simply trying to get the @id attribute of the first and the last <gig/> node? In which case, forget about attributes() and use SimpleXML's notation instead: attributes are accessed as if they were array keys.

$first_id = $xml->gig[0]['id'];
$last_id  = $xml->gig[count($xml->gig) - 1]['id'];


I think that this xpath expression should work

$xml->xpath('root/child[last()]');

That should retrieve the last child element that is a child of the root element.

0

精彩评论

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

关注公众号