我想对 SimpleXML 对象中的每个节点应用一个函数。
<api>
<stuff>ABC</stuff>
<things>
<thing>DEF</thing>
<thing>GHI</thing>
<thing>JKL</thing>
</things>
</api>
//函数reverseText($str){};
<api>
<stuff>CBA</stuff>
<things>
<thing>FED</thing>
<thing>IHG</thing>
<thing>LKJ</thing>
</things>
</api>
我如何将 reverseText() 应用于每个节点以获取第二个 XML 片段?
最佳答案
这里是 Standard PHP Library可以前来救援。
一个选择是使用(鲜为人知的)SimpleXMLIterator
.它是几个 RecursiveIterator
之一在 PHP 和 RecursiveIteratorIterator
中可用来自 SPL 的可用于循环并更改所有元素的文本。
$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();
上面的例子输出如下:
<?xml version="1.0"?>
<api>
<stuff>CBA</stuff>
<things>
<thing>FED</thing>
<thing>IHG</thing>
<thing>LKJ</thing>
</things>
</api>
关于用于 SimpleXML 对象的 PHP array_walk_recursive()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17095484/