How do you exclude the XML prolog from output? [du

2019-08-01 15:53发布

问题:

This question already has an answer here:

  • PHP DomDocument output without <?xml version=“1.0” encoding=“UTF-8”?> 3 answers

I write $xml = new DOMDocument(); and it automatically creates <?xml version="1.0"?>. I need to NOT create it. How do i do that?

One solution is to search the first ">" and strsub at the index at the first < found. But i like a nicer way to do this.

回答1:

When you saveXML, pass in the root element as the node argument. Only the root element and its contents will be serialised, and not any XML declaration, doctype, comments or PIs outside the root.

$doc->saveXML($doc->documentElement);

or, if you need the other stuff but just not the redundant declaration:

$result= '';
foreach($document->childNodes as $node)
    $result.= $document->saveXML($node)."\n";