Is it possible to insert a comment tag in xml using simplexml?

I use SimpleXML to create a document and wonder if it is possible to insert a comment tag in a document as follows:

<root> <!-- some comment --> <value> </root> 

EDIT

The comment is somewhere in the middle of the document.

 <root> <tag1 /> <!-- some comment --> <value /> </root> 
+7
xml php simplexml
source share
4 answers

Unfortunately, SimpleXML does not process comments. As already mentioned, the DOM processes comments, but compared to SimpleXML, this is a kind of useless activity for simple things.

My recommendation: try SimpleDOM . This is a SimpleXML extension, so everything works the same way, and it has tons of useful methods for working with the DOM.

For example, insertComment($content, $mode) can append or insert comments before or after given node. For example:

 include 'SimpleDOM.php'; $root = simpledom_load_string('<root><value/></root>'); $root->value->insertComment(' mode: append ', 'append'); $root->value->insertComment(' mode: before ', 'before'); $root->value->insertComment(' mode: after ', 'after'); echo $root->asPrettyXML(); 

... will be an echo

 <?xml version="1.0"?> <root> <!-- mode: before --> <value> <!-- mode: append --> </value> <!-- mode: after --> </root> 
+6
source share

No, but obviously you can use DomDocument as a workaround (German) :

  $oNodeOld = dom_import_simplexml($oParent); $oDom = new DOMDocument(); $oDataNode = $oDom->appendChild($oDom->createElement($sName)); $oDataNode->appendChild($oDom->createComment($sValue)); $oNodeTarget = $oNodeOld->ownerDocument->importNode($oDataNode, true); $oNodeOld->appendChild($oNodeTarget); return simplexml_import_dom($oNodeTarget); 

But then again, why not use the DOM directly?

+5
source share

Actually there is a dirty trick based on the fact that addChild does not check if the element name is valid:

 $root->addChild('!-- Your comment --><dummy'); 

When using $root->asXML() you will get a line like this:

 <root><!-- Your comment --><dummy/></root> 

You may notice that it generated an empty <dummy> element, but this is the price you have to pay. Do not try to add value, it will only hurt everything. Use only in conjunction with asXML() .

Ok, I said this is a dirty trick. I do not recommend using this in production , but only for debugging / testing purposes.

+4
source share

Here is a quick and easy solution:

 $xml = new SimpleXMLElement('<root/>'); $xml->element->comment->sample = 12; $xml_str = $xml->asXML(); $xml_str = str_replace(['<comment>', '</comment>'], ['<!--', '-->'], $xml_str) echo $xml_str; 

 <root> <!-- <sample>12</sample> --> </root> 
0
source share

All Articles