Search code examples
phpdomdocument

PHP DomDocument output without <?xml version="1.0" encoding="UTF-8"?>


is there an option with DomDocument to remove the first line:

<?xml version="1.0" encoding="UTF-8"?>

The class instantiation automatically adds it to the output, but is it possible to get rid of it?


Solution

  • If you want to output HTML, use the saveHTML() function. It automatically avoids a whole lot of XML idiom and handles closed/unclosed HTML idiom properly.

    If you want to output XML you can use the fact that DOMDocument is a DOMNode (namely: '/' in XPath expression), thus you can use DOMNode API calls on it to iterate over child nodes and call saveXML() on each child node. This does not output the XML declaration, and it outputs all other XML content properly.

    Example:

    $xml = get_my_document_object();
    foreach ($xml->childNodes as $node) {
       echo $xml->saveXML($node);
    }