How can the use of DOMDocument and DOMXpath in PHP improve the efficiency of extracting data from HTML pages?

Using DOMDocument and DOMXpath in PHP can improve the efficiency of extracting data from HTML pages by providing a more structured and reliable way to navigate and manipulate the HTML DOM tree. DOMDocument allows you to load an HTML document into a DOM object, which can then be queried using DOMXpath to easily locate specific elements or attributes within the document. This approach is more robust than using string manipulation or regular expressions, as it ensures proper handling of HTML structure and syntax.

// Create a new DOMDocument object
$dom = new DOMDocument();

// Load the HTML content from a file or URL
$dom->loadHTMLFile('example.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 extract data
foreach ($elements as $element) {
    echo $element->textContent;
}