append encoding on creation of xml file
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 encoding
value in the output of saveHTML()
, you can set the encoding
property.
$xmldoc->load('test.xml');
$xmldoc->encoding= 'utf-8';
$xmldoc->save('test.xml');
However, as Artefacto said, in this case it's pointless. An XML file without an <?xml encoding
declaration 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 explicit encoding="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-Type
header. But in that case the <?xml encoding
declaration is ignored anyway.)
If you are trying to create a new UTF-8 encoded file, this should work:
$xmldoc = new DomDocument('1.0', 'UTF-8');
if(file_exists('test.xml')){
$xmldoc->load('test.xml');
} else {
$xmldoc->loadXML('<root/>');
}
But if you are opening a file that is not encoded in UTF-8, you'll have problems with the output... so you'll want to check the encoding of the file if it exists, and if not, you can create it as UTF-8.
OK:
<?php
$xmlDoc = new DOMDocument('1.0', 'utf-8');
print $xmlDoc->saveXML();
?>
outputs:
<?xml version="1.0" encoding="utf-8"?>
The answer by bobince is correct and great help.
you can also read $dom->encoding from the file you read or grab.
I also output it with the header();
$xmldoc->load('test.xml');
$encoding = $dom->encoding;
/* ... manipulate dom ... */
header("Content-Type: application/xml; charset=". $encoding);
echo $dom->saveXML();
精彩评论