this code creates an xml file if it does not exist:
$xmldoc = new DOMDocument();
if(file_exists('test.xml')){
$xmldoc->load('test.xml');
} else {
$xmldoc->loadXML('<root/>');
}
however, i would also like encoding="UTF-8" to be appended automatically on creation of the file. how would one do this in php?
To add/change the
<?xml encodingvalue in the output ofsaveHTML(), you can set theencodingproperty.However, as Artefacto said, in this case it’s pointless. An XML file without an
<?xml encodingdeclaration or a UTF-16 BOM is definitely UTF-8 and all XML parsers will read it that way(*). You will gain nothing by adding an explicitencoding="utf-8"parameter to the XML Declaration.Whatever the method is you’re using to test, it’s not doing what you think it’s doing. Maybe you’re loading XML into a text editor and it’s saving it out in a different encoding, or something? You need to look at where you’re getting the strings from that are going into the DOM before you save it, and if they’re not UTF-8 you need to convert them then.
(*: Well unless it’s served via another protocol with a higher-priority charset specification method, like HTTP’s
Content-Typeheader. But in that case the<?xml encodingdeclaration is ignored anyway.)