Here the Standard PHP Library can come to the rescue.
One option is to use the (little known) SimpleXMLIterator
. It is one of several RecursiveIterator
s available in PHP and a RecursiveIteratorIterator
from the SPL can be used to loop over and change all of the elements' text.
$source = '
<api>
<stuff>ABC</stuff>
<things>
<thing>DEF</thing>
<thing>GHI</thing>
<thing>JKL</thing>
</things>
</api>
';
$xml = new SimpleXMLIterator($source);
$iterator = new RecursiveIteratorIterator($xml);
foreach ($iterator as $element) {
// Use array-style syntax to write new text to the element
$element[0] = strrev($element);
}
echo $xml->asXML();
The above example outputs the following:
<?xml version="1.0"?>
<api>
<stuff>CBA</stuff>
<things>
<thing>FED</thing>
<thing>IHG</thing>
<thing>LKJ</thing>
</things>
</api>