PHP array_walk_recursive () for SimpleXML objects?

I would like to apply a function to each node in a SimpleXML object.

<api> <stuff>ABC</stuff> <things> <thing>DEF</thing> <thing>GHI</thing> <thing>JKL</thing> </things> </api> 

// function reverseText ($ str) {};

 <api> <stuff>CBA</stuff> <things> <thing>FED</thing> <thing>IHG</thing> <thing>LKJ</thing> </things> </api> 

How to apply reverseText () method to each node to get a second XML fragment?

+4
source share
2 answers

Here the PHP Standard Library can come to the rescue.

One option is to use the (little-known) SimpleXMLIterator . This is one of several RecursiveIterator available in PHP, and the RecursiveIteratorIterator from SPL can be used to iterate and change the text of all elements.

 $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 displays the following:

 <?xml version="1.0"?> <api> <stuff>CBA</stuff> <things> <thing>FED</thing> <thing>IHG</thing> <thing>LKJ</thing> </things> </api> 
+11
source

You can create an array of all nodes in the document using the SimpleXMLElement::xpath() method.

Then you can use array_walk in this array. However, you do not want to change the row of each node only for those elements that do not have children.

 $source = ' <api> <stuff>ABC</stuff> <things> <thing>DEF</thing> <thing>GHI</thing> <thing>JKL</thing> </things> </api> '; $xml = new SimpleXMLElement($source); array_walk($xml->xpath('//*'), function(&$node) { if (count($node)) return; $node[0] = strrev($node); }); echo $xml->asXML(); 

The above example displays the following:

 <?xml version="1.0"?> <api> <stuff>CBA</stuff> <things> <thing>FED</thing> <thing>IHG</thing> <thing>LKJ</thing> </things> </api> 

The xpath query allows more control, for example, with namespaces.

0
source

Source: https://habr.com/ru/post/1486101/


All Articles