How can PHP developers efficiently parse HTML content using DOMDocument and XPath instead of using outdated functions like str_get_html?

When parsing HTML content in PHP, developers can efficiently use DOMDocument and XPath instead of outdated functions like str_get_html. DOMDocument allows for easy traversal and manipulation of HTML elements, while XPath provides a powerful querying language to navigate the DOM structure. By combining these two tools, developers can parse HTML content more efficiently and reliably.

// 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 selected elements
foreach ($elements as $element) {
    // Do something with the element
    echo $element->nodeValue;
}