LibXMLError XML declaration allowed only at the start of the document
From the image and code in the question is seems like what you have in your document is this:
<xmp> <?xml version="1.0"?> <workout>
That is, the root element of the document you’re feeding to simplexml_load_string
is <xmp>
, not <workout>
. So LibXML starts parsing that document from the <xmp>
element, then hits the <?xml version="1.0"?>
and says, Hey that’s an XML declaration—that shouldn’t be here.
To prevent the XML declaration from getting added, you can replace your $xml->saveXML()
with:
foreach ($xml->childNodes as $node) { echo $xml->saveXML($node);}
Or see some of the other answers for the questions PHP DomDocument output without <?xml version="1.0" encoding="UTF-8"?> and remove xml version tag when a xml is created in php.
The idea is just that instead of outputting the whole thing as a document, your code instead iterates through all nodes of the document starting with the root and outputs them one-by-one in order.
So because you’re outputting individual nodes that way instead of the whole document as a document, that skips the unwanted XML declaration at the beginning for the document.
An alternative that may also work is, make saveXML(…)
only emit the document element (root):
$xml->saveXML($xml->documentElement)
If it works, it’ll emit your workout
element and all its descendants, skipping the XML declaration.