Search code examples
phpxmlsimplexml

Is there any way to retrieve the comments from an XML file?


Is there any way to retrieve the comments from an XML file?

I have an XML file, with comments in it, and i have to build an user-interface based on each node in this file, and the associated comments.

I can't seem to find a way to get those comments. I was able to get 'some' of them using simpleXML, but it didn't work for the root node, and was acting pretty strange... some comments were put in their own node, some other were left as childs, and all comments were put in the same node... Not sure this makes any sense:) the point is simpleXML broke the structure of the comments and it wasn't good for my needs.


Solution

  • You can use XMLReader to read through all of the nodes and pull out the comments. I've included some sample code to get you started, as it just pulls out the nodes, and doesn't take into account where the comment is inside, below or above any xml nodes.

    $comments = '';
    $xml =<<<EOX
    <xml>
        <!--data here -->
        <data>
            <!-- more here -->
            <more />
        </data>
    </xml>
    EOX;
    
    $reader = new XMLReader();
    $reader->XML($xml);
    
    while ($reader->read()) {
      if ($reader->nodeType == XMLReader::COMMENT) {
          $comments .= "\n".$reader->value;
      }
    }
    
    $reader->close();
    
    echo "all comments below:\n-------------------".$comments
    

    The expected output is:

    all comments below:
    -------------------
     data here
     more here
    

    So just the values of the comments (not the <!-- -->) will be taken, as well as whitespace.