How to access <tag> by its id attribute and not array position?

Issue

I would like to understand how to access a <tag> by its id and not through array position. Example:

<someNameHere id="hello">
 <home>
 </home>
 <home>
 </home>
</someNameHere>
<someNameHere id="hi">
 <home>
 </home>
 <home>
 </home>
</someNameHere>

I don’t want to do this:

$myXML->someNameHere[1]->home[0]

I want to go access someNameHere by its ID "hi".

Solution

You’ll have to use XPath for that.

$nodes = $myXML->xpath('//*[@id="hi"]');

if (!empty($nodes))
{
    $someNameHere = $nodes[0];
}

Answered By – Josh Davis

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published