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.
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