How can the DOMDocument and DOMXPath classes be utilized to manipulate HTML content in PHP?

To manipulate HTML content in PHP, the DOMDocument class can be used to load the HTML content into a DOM object, which can then be manipulated using methods provided by the class. The DOMXPath class can be used in conjunction with DOMDocument to query specific elements in the HTML content using XPath expressions.

// Load HTML content into a DOMDocument object
$html = '<html><body><div id="content">Hello, World!</div></body></html>';
$dom = new DOMDocument();
$dom->loadHTML($html);

// Use DOMXPath to query specific elements
$xpath = new DOMXPath($dom);
$elements = $xpath->query('//div[@id="content"]');

// Manipulate the content of the queried elements
foreach ($elements as $element) {
    $element->nodeValue = 'Hello, PHP!';
}

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