PHP 中的 SimpleXML;将节点替换为文本节点
给定这个 XML/XHTML 片段:
<h1>
<zuq:data name="siteHeader" />
</h1>
<h2>
<zuq:data name="pageHeaderName" />
<span>—</span>
<zuq:data name="pageHeaderTitle" />
</h2>
我使用 SimpleXML 的 XPath 方法来四舍五入 zuq
命名空间中的所有顶级节点。由于 xpath() 方法的数组元素是对 SimpleXML 对象树节点的伪引用,因此我认为操作会很容易。但是,我无法弄清楚如何用文本节点替换给定的元素节点。例如,我如何将
替换为文本 My Site Header
。
我考虑过简单地定位父节点并修改其内容,以便可以与第一个块 (
) 一起使用,但在考虑到我的第二个块的情况下,我认为这不起作用 (
)。
)。有没有一种简单的方法可以通过 PHP 中的 SimpleXML
将给定元素节点替换为文本节点?
Given this XML/XHTML snippet:
<h1>
<zuq:data name="siteHeader" />
</h1>
<h2>
<zuq:data name="pageHeaderName" />
<span>—</span>
<zuq:data name="pageHeaderTitle" />
</h2>
I've used SimpleXML's XPath method to round up all top-level nodes in the zuq
namespace. Since the array elements of the xpath()
method are pseudo references to the SimpleXML
object tree nodes, I figured manipulation would be easy. However, I cannot figure out how to replace a given element node with a text node. How could I, for example, replace <zuq:data name="siteHeader" />
with the text My Site Header
.
I've considered simply targeting the parent node and modifying it's contents as could work with the first block (<h1>
), but I don't see that working given the case of my second block (<h2>
).
Is there an easy way to replace a given element node with a text node via SimpleXML
in PHP?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
据我所知,simplexml 不具备删除或替换节点的功能。它更适合阅读、创建和非结构相关的编辑。您必须使用 DOM XML 对象来完全替换节点。它有点像 simplexml 的更复杂版本。在这里阅读:
http://www.php.net/manual/en/ book.domxml.php
as far as i know, simplexml doesn't have the capability to remove or replace nodes. it's more for reading, creating, and non-structure related edits. you will have to use a DOM XML object to fully replace nodes. it's sort of like a more complex version of simplexml. read about it here:
http://www.php.net/manual/en/book.domxml.php
快速查看文档我也找不到简单的方法。我会尝试迭代原始 xml 文档并将每个元素复制到新的 xml 文档,并根据需要修改它们。
Quickly looking at the documentation I was not able to find a simple way either. I would try to just iterate over the original xml doc and copy each element to a new xml doc, modifying them as necessary.