更改根 SimpleXML 元素的文本 [英] Change text of root SimpleXML Element
问题描述
我正在尝试创建一个简单的包装函数,用于以 XML 格式为现有 Flash 应用程序输出我的错误.我已经读过 SimpleXMLElement
不一定用于创建新的 XML 文档,但到目前为止它对我来说工作正常,我基本上是在替换连接的字符串.
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>
但我看到了这个:
<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();
似乎使用 $obj->node
语法创建了一个子节点.我可以实例化 SimpleXMLElement
的唯一方法是传递父节点.
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.
推荐答案
结果在意料之中.您的 $sxml
是根节点,例如<ERROR/>
- 使用对象运算符将导航到子元素(如果存在)或添加该名称的新元素(如果它不存在).由于根 ERROR 节点下面没有 ERROR 元素,所以添加了它.
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:
$msg = 'There is an error';
$xmlstr = "<ERROR></ERROR>";
$sxml = new SimpleXMLElement($xmlstr);
$sxmlErr = $sxml[0] = $msg;
echo $sxml->asXML();
不落入根元素陷阱的一个好习惯是使用根元素的名称作为保存它的变量名称,例如
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.
$error = new SimpleXMLElement('<ERROR/>');
$error[0] = 'There is an Error';
echo $error->asXML();
另见一个简单的程序到 CRUD 节点和 xml 文件的节点值
这篇关于更改根 SimpleXML 元素的文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!