tags:

views:

255

answers:

4

Hi ,

I want to find the 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

+1  A: 

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){
}
Frank Bollack
Unfortunately, array dereferencing like that (`func()[0]`) is not valid PHP syntax (at the time of writing this). To keep the one-liner, the `current` function could be used (assuming there is always at least one `gig` node). Also the OP wants the last gig which is an immediate child of the root node (or at least that's what it sounds like they want).
salathe
@salathe: Ah, thanks for the advice. It's not my natural language ;-)
Frank Bollack
+1  A: 

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);
salathe
foreach (current($xml->xpath('/*/gig[last()]'))->attributes() as $attr) {}only displays the attribute from the first node not the last.
Oliver Bayes-Shelton
Unless the first node is also the last, or your definition of last differs from mine, there's something odd going on. We explicitly ask for the last gig node in the XPath expression.
salathe
+1  A: 

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'];
Josh Davis
A: 

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.

JC