How can DOMDocument and XPath be utilized in PHP to achieve the desired text manipulation within specific HTML elements?

To achieve text manipulation within specific HTML elements using DOMDocument and XPath in PHP, you can load the HTML content into a DOMDocument object, use XPath to query for the desired elements, and then manipulate the text content accordingly.

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

// Create a DOMXPath object to query the DOMDocument
$xpath = new DOMXPath($doc);

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

// Loop through the selected elements and manipulate the text content
foreach ($elements as $element) {
    $element->nodeValue = "New text content";
}

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