Search code examples
xmlencodingutf-8domdocumentxmldom

XML File generated with DOMDocument not showing encoding


$doc = new DOMDocument('1.0', 'UTF-8');
$doc->xmlStandalone = true;
$doc->loadXML($error);
echo $doc->saveXML();

Output

<?xml version="1.0"?>
<error status="fatal" httpResponseCode="500" httpResponseMessage="Internal Server Error">
        <errorType>InternalServerError</errorType>
        <errorServer>FeedServer</errorServer>
        <errorMessage>Failed to process GetFeed request</errorMessage>
        <friendlyMessage/>
        <innerMessage>No permitted outlet found</innerMessage>
</error>

I need the XML output should show the encoding="UTF-8" along with the version="1.0" Please help...

AFTER FIXED.....

$doc    = new DOMDocument('1.0', 'UTF-8');
$doc->loadXML($error);
$doc->xmlStandalone = true;
$doc->encoding = 'UTF-8';
echo $doc->saveXML(); 

THE DESIRED OUTPUT...

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<error status="fatal" httpResponseCode="500" httpResponseMessage="Internal Server Error">
        <errorType>InternalServerError</errorType>
        <errorServer>FeedServer</errorServer>
        <errorMessage>Failed to process GetFeed request</errorMessage>
        <friendlyMessage/>
        <innerMessage>No permitted outlet found</innerMessage>
</error>

Solution

  • The parameters in the new DOMDocument constructor are overwritten with the values from the loaded XML document when loadXML is called.

    If you set the encoding of the output document (e.g. $doc->encoding = 'UTF-8', before calling saveXML), it should be added to the XML declaration.