更改根 SimpleXML 元素的文本
我正在尝试创建一个简单的包装函数,用于为现有 Flash 应用程序输出 XML 中的错误。我已经读到 SimpleXMLElement
不一定用于创建新的 XML 文档,但到目前为止它对我来说工作得很好,而且我基本上是在替换连接的字符串。
到目前为止,我在迭代和添加/修改属性、值等方面没有遇到任何问题。在这个示例中,我希望看到我的输出如下所示:
<ERROR>There is an error</ERROR>
但我看到的是:
<ERROR>
<ERROR>There is an error</ERROR>
</ERROR>
这是代码:
$msg = 'There is an error';
$xmlstr = "<ERROR></ERROR>";
$sxml = new SimpleXMLElement($xmlstr);
$sxmlErr = $sxml->ERROR = $msg;
echo $sxml->asXML();
似乎使用 < code>$obj->node 语法创建一个子节点。实例化 SimpleXMLElement
的唯一方法是传递父节点。
I'm trying to create a simple wrapper function for outputting my errors in XML for an existing Flash application. I've already read that SimpleXMLElement
is not necessarily intended for creating a new XML document but it's working fine for me so far and I am basically replacing concatenated strings.
Up until now I've had no problems iterating and adding/modifying attribues, values, etc. In this example I would like to see my output look like this:
<ERROR>There is an error</ERROR>
But I am seeing this:
<ERROR>
<ERROR>There is an error</ERROR>
</ERROR>
Here's the code:
$msg = 'There is an error';
$xmlstr = "<ERROR></ERROR>";
$sxml = new SimpleXMLElement($xmlstr);
$sxmlErr = $sxml->ERROR = $msg;
echo $sxml->asXML();
It seems that using the $obj->node
syntax creates a child node. And the only way I can instantiate a SimpleXMLElement
is by passing the parent node.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
结果是预期的。您的
$sxml
是根节点,例如
- 使用对象运算符将导航到子元素(如果存在)或添加新元素该名称的元素(如果不存在)。由于根 ERROR 节点下面没有 ERROR 元素,因此添加它。通过索引访问根节点:
避免陷入根元素陷阱的一个好习惯是使用根元素的名称作为保存它的变量名称,例如
另请参阅 一个对 xml 文件的 CRUD 节点和节点值进行 CRUD 的简单程序
The result is expected. Your
$sxml
is the root node, e.g.<ERROR/>
- using the object operator will either navigate to a child element (if it exists) or add a new element of that name (if it doesnt exist). Since there is no ERROR element below the root ERROR node, it is added.Access the root node by index instead:
A good practise to not fall into that root element trap is to use the root element's name as the variable name that holds it, e.g.
Also see A simple program to CRUD node and node values of xml file