How can DOMXPath be utilized to simplify the extraction of specific elements from HTML in PHP?

When extracting specific elements from HTML in PHP, using DOMXPath can simplify the process by allowing you to query the HTML document using XPath expressions. This makes it easier to target specific elements based on their attributes or structure.

// Load the HTML content into a DOMDocument
$html = file_get_contents('example.html');
$dom = new DOMDocument();
$dom->loadHTML($html);

// Create a new DOMXPath object
$xpath = new DOMXPath($dom);

// Use XPath query to select specific elements
$elements = $xpath->query('//div[@class="content"]');

// Loop through the selected elements and output their content
foreach ($elements as $element) {
    echo $element->nodeValue . "\n";
}