I am using SimpleXML to build a document, and wondering whether it is possible to insert comment tag to the document like this:
<root>
<!-- some comment -->
<value>
</root>
EDIT:
The comment is somewhere in the middle of the document.
<root>
<tag1 />
<!-- some comment -->
<value />
</root>
There's actually a dirty trick, based on the fact that
addChild
doesn't check if the element name is valid:When using
$root->asXML()
you'd get a string like this:You may notice it generated an empty
<dummy>
element as well, but it's the price to pay. Don't try to add a value, it would only mess everything up. Use only in conjunction withasXML()
.Well, I did say it's a dirty trick. I don't recommend using this in production, but only for debugging/testing purposes.
Nope, but apparently you can use DomDocument as a workaround (german):
But then again, why not use DOM directly?
Unfortunately, SimpleXML doesn't handle comments. As it's been mentionned, DOM does handle comments but it's a kind of a bother to use for simple stuff, compared to SimpleXML.
My recommendation: try SimpleDOM. It's an extension to SimpleXML, so everything works the same and it has a bunch of useful methods to deal with DOM stuff.
For instance,
insertComment($content, $mode)
canappend
to or insert commentsbefore
orafter
a given node. For example:...will echo
Here is a quick and easy solution: