Change text of root SimpleXML Element

2019-07-07 05:02发布

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.

1条回答
一纸荒年 Trace。
2楼-- · 2019-07-07 05:43

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();

Also see A simple program to CRUD node and node values of xml file

查看更多
登录 后发表回答