用于 SimpleXML 对象的 PHP array_walk_recursive()?

标签 php simplexml spl

我想对 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/

相关文章:

php - 使用 RecursiveDirectoryIterator 对目录列表进行排序

php - 是否可以在 php 中序列化 SplEnum

php - 使用 PHP 连接到 IRC 服务器时连接超时

php - 更新查询在 mysql 中抛出错误

php - 为什么 PDOStatement 在单次获取时返回 false?

php - 用户提交前 5 名并按受欢迎程度排序

PHP SimpleXML - xpath 不起作用,但在在线生成器中它可以

php - 如何获取 simplexml 对象的所有元素

php - 用于使用 PHP 解析 xml 文件的 simpleXML 的替代方法

php - SPL 自动加载最佳实践