Find XML Nodes and Attributes with PHP SimpleXML Recursive Functions

How to find XML nodes and attributes by name with PHP SimpleXML traversing recursively an xml file

Traverse an xml file to get the nodes and attributes values. The function findXMLNode loops recursively through all the xml nodes and return the value that matches the node name. And the function findXMLAttr loops recursively through all the xml attributes and return the value that matches the attributes name.


main.xml

<?xml version="1.0" encoding="UTF-8"?>
<main>
    <parent age="30">
        <child1>I am child one</child1>
        <child2>I am child two</child2>
    </parent>
</main>




Php code:

function findXMLNode( $xml, $nodeName )
{
    foreach($xml->children() as $child) {
        foreach($child as $name => $val) {
            if($name == $nodeName) {
               
                return $val;
            }
        }
        findXMLNode($child,$nodeName);
    }
}

function findXMLAttr( $xml, $attrName )
{
    foreach($xml->children() as $child) {
        foreach($child->attributes() as $attr => $attrVal) {
            if($attr == $attrName) { 
               
                return $attrVal;
            }
        }
        findXMLAttr( $child,$attrName );      
    }
}

// Test
$oXML = new SimpleXMLElement(file_get_contents('main.xml'));

// Look for xml node "child1" value
print "\nNode: ".findXMLNode($oXML,"child1");

// Look for xml attribute "age" value
print "\nAttr: ".findXMLAttr($oXML,"age");

/*
Will output:

Node: I am child one
Attr: 30
*/