Search code examples
phpxmlsimplexml

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


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>

Solution

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