A call to loadXML() will overwrite the XML declaration previously created in the constructor of DOMDocument. This can cause encoding problems if there is no XML declaration in the loaded XML and you don't have control over the source (e.g. if the XML is coming from a webservice). To fix this, set encoding AFTER loading the XML using the 'encoding' class property of DOMDocument. Example:
Bad situation:
test.xml:
<test>
<hello>hi</hello>
<field>ø</field>
</test>
test.php:
$xmlDoc = new DOMDocument("1.0", "utf-8"); // Parameters here are overwritten anyway when using loadXML(), and are not really relevant
$testXML = file_get_contents("test.xml");
$xmlDoc->loadXML($testXML);
// Print the contents to a file or in a log function to get the output, using $xmlDoc->saveXML()
Output:
<?xml version="1.0"?>
<test>
<hello>hi</hello>
<field>ø</field>
</test>
Good situation:
test.xml:
<test>
<hello>hi</hello>
<field>ø</field>
</test>
test.php:
$xmlDoc = new DOMDocument("1.0", "utf-8"); // Parameters here are overwritten anyway when using loadXML(), and are not really relevant
$testXML = file_get_contents("test.xml");
$xmlDoc->loadXML($testXML);
$xmlDoc->encoding = "utf-8";
// Print the contents to a file or in a log function to get the output, using $xmlDoc->saveXML()
Output:
<?xml version="1.0" encoding="utf-8"?>
<test>
<hello>hi</hello>
<field>ø</field>
</test>