What are best practices for optimizing HTML parsing in PHP, such as using DOMDocument and XPath?

When parsing HTML in PHP, using DOMDocument and XPath can greatly improve performance and simplify the process of extracting specific elements from the HTML document. DOMDocument provides a convenient way to load and manipulate HTML documents, while XPath allows for easy querying of specific elements based on their attributes or structure.

// 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);

// Query for specific elements using XPath
$elements = $xpath->query('//div[@class="content"]');

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