tags:

views:

106

answers:

3

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>
A: 

Yes you can XML comments have the exact same syntax as HTML comments.

http://www.tizag.com/xmlTutorial/xmlcomment.php

Gerard Banasig
I think the OP wants to know how to do it with SimpleXml, not if it is valid XML at all.
Gordon
+2  A: 

Nope, but apparently 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 DOM directly?

Gordon
+1  A: 

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) can append to or insert comments before or after a 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 echo

<?xml version="1.0"?>
<root>
  <!-- mode: before -->
  <value>
    <!-- mode: append -->
  </value>
  <!-- mode: after -->
</root>
Josh Davis