What are the best practices for using DOMDocument and DOMXPath in PHP for manipulating HTML content?

When manipulating HTML content in PHP, using DOMDocument and DOMXPath allows for easy traversal and manipulation of the DOM structure. Best practices include loading the HTML content into a DOMDocument object, using DOMXPath to query specific elements, and then making changes to the DOM structure as needed.

// Load the HTML content into a DOMDocument object
$doc = new DOMDocument();
$doc->loadHTML($html_content);

// Use DOMXPath to query specific elements
$xpath = new DOMXPath($doc);
$elements = $xpath->query('//div[@class="example"]');

// Make changes to the DOM structure
foreach ($elements as $element) {
    $new_element = $doc->createElement('p', 'New paragraph content');
    $element->parentNode->replaceChild($new_element, $element);
}

// Output the modified HTML content
echo $doc->saveHTML();