3v4l.org

run code in 300+ PHP versions simultaneously
<?php $html = <<<'HTML' <html> <head> </head> <body id="body"> <div>text1</div> <div>text2</div> </body> </html> HTML; $dom = new DOMDocument(); $dom->loadHtml($html); $xpath = new DOMXpath($dom); $nodes = $xpath->evaluate('//text()[contains(., "text1")]'); foreach ($nodes as $node) { $ancestors = $xpath->evaluate('ancestor::*', $node); $path = ''; foreach ($ancestors as $ancestorNode) { $tagName = $ancestorNode->tagName; $path .= '/'.$tagName; } var_dump($path); }

preferences:
33.14 ms | 402 KiB | 5 Q