How can DOMDocument and DOMXPath be used to simplify the process of manipulating HTML elements in PHP?

When manipulating HTML elements in PHP, using DOMDocument and DOMXPath can simplify the process by providing a structured way to access and modify elements within an HTML document. DOMDocument allows for parsing and creating HTML documents, while DOMXPath enables querying and navigating through the document using XPath expressions. By combining these two classes, developers can easily locate specific elements in the HTML document and make desired changes.

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

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

// Create a new DOMXPath object
$xpath = new DOMXPath($doc);

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

// Loop through selected elements and make changes
foreach ($elements as $element) {
    $element->setAttribute('style', 'color: red;');
}

// Save the modified HTML content
$modified_html = $doc->saveHTML();