Skip to content
PHP Logo

How can DOMDocument and DOMXPath be used to manipulate text in PHP?

To manipulate text using DOMDocument and DOMXPath in PHP, you can load the HTML content into a DOMDocument object, use DOMXPath to query for specific elements containing the text you want to manipulate, and then update the text content as needed.

php
<?php
// Load the HTML content into a DOMDocument object
$doc = new DOMDocument();
$doc->loadHTML($htmlContent);

// Use DOMXPath to query for specific elements containing the text you want to manipulate
$xpath = new DOMXPath($doc);
$elements = $xpath->query('//p[contains(text(), "example")]');

// Update the text content of the selected elements
foreach ($elements as $element) {
    $element->nodeValue = str_replace('example', 'new text', $element->nodeValue);
}

// Get the updated HTML content
$updatedHtmlContent = $doc->saveHTML();
?>