Search code examples
phpattributessimplexml

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


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];
    }