genespos
genespos

Reputation: 3311

Get xml node full path in Php / SimpleXml

I need the full path of an xml node.
I saw the answer in this question but I wasn't able to use it.

Below the code I used on a php web tester with no success:

$xml = <<<EOF
<root>
    <First>
        <Martha>Text01</Martha>
        <Lucy>Text02</Lucy>
        <Bob>
            <Jhon>Text03</Jhon>
        </Bob>
        <Frank>One</Frank>
        <Jessy>Two</Jessy>
    </First>
    <Second>
        <Mary>
            <Jhon>Text04</Jhon>
            <Frank>Text05</Frank>
            <Jessy>Text06</Jessy>
        </Mary>
    </Second>
</root>
EOF;

$MyXml = new SimpleXMLElement($xml);
$Jhons = $MyXml->xpath('//Jhon');
foreach ($Jhons as $Jhon){
    echo (string) $Jhon;
    //No one of the following works
    echo (string) $Jhon->xpath('./node()/path()');
    echo (string) $Jhon->xpath('./path()');
    echo (string) $Jhon->xpath('.path()');
    echo (string) $Jhon->path();
    echo '<br/> ';
}

I need: "/root/First/Bob/Jhon" and "/root/Second/Mary/Jhon"

Upvotes: 0

Views: 2185

Answers (1)

Nigel Ren
Nigel Ren

Reputation: 57141

You can use the much more powerful DOM (DOMDocument based in PHP) api to do this...

$MyXml = new SimpleXMLElement($xml);
$Jhons = $MyXml->xpath('//Jhon');
foreach ($Jhons as $Jhon){
    $dom = dom_import_simplexml($Jhon);
    echo $dom->getNodePath().PHP_EOL;
}

The dom_import_simplexml($Jhon) converts the node and then getNodePath() displays the path...

This gives ( for the example)

/root/First/Bob/Jhon
/root/Second/Mary/Jhon

Or if you just want to stick to SimpleXML, you can use the XPath axes ancestor-or-self to list the current node and each parent node...

$MyXml = new SimpleXMLElement($xml);
$Jhons = $MyXml->xpath('//Jhon');
foreach ($Jhons as $Jhon){
    $parent = $Jhon->xpath("ancestor-or-self::*");
    foreach ( $parent as $p )   {
        echo "/".$p->getName();
    }
    echo PHP_EOL;
}

Upvotes: 5

Related Questions