What are the advantages of using DOMXPath for extracting specific elements from HTML in PHP?

When extracting specific elements from HTML in PHP, using DOMXPath can be advantageous because it allows for more precise and flexible searching within the HTML document. DOMXPath provides a way to query the DOM document using XPath expressions, which can target specific elements based on their attributes or position in the document. This makes it easier to extract the desired information without having to manually parse through the entire HTML structure.

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

$dom = new DOMDocument();
$dom->loadHTML($html);

$xpath = new DOMXPath($dom);
$elements = $xpath->query("//div[@class='content']/p");

foreach ($elements as $element) {
    echo $element->nodeValue . "\n";
}
?>