What are the advantages of using XPath over Simple HTML DOM in PHP for targeting specific elements?

When targeting specific elements in HTML documents, using XPath in PHP provides more flexibility and power compared to Simple HTML DOM. XPath allows for more complex and precise querying of elements based on their attributes, position in the document, and relationships to other elements. This makes it easier to target specific elements even in large and complex HTML structures.

<?php
$html = '<div id="content">
            <h1>Title</h1>
            <p>Paragraph 1</p>
            <p>Paragraph 2</p>
        </div>';

$doc = new DOMDocument();
$doc->loadHTML($html);
$xpath = new DOMXPath($doc);

// Targeting all <p> elements within the <div id="content">
$paragraphs = $xpath->query('//div[@id="content"]/p');

foreach ($paragraphs as $paragraph) {
    echo $paragraph->nodeValue . "<br>";
}
?>