|
php.net | support | documentation | report a bug | advanced search | search howto | statistics | random bug | login |
[2008-12-03 11:41 UTC] sites at hubmed dot org
Description:
------------
Using $xml->asXML() to output an XML document as a string from SimpleXML seems to be defaulting to ISO 8859-1 rather than UTF-8, despite all other operations being in UTF-8 (and with LANG and LC_ALL being set to UTF-8).
There is a workaround, by manually setting '<?xml version="1.0" encoding="UTF-8"?>' at the start of any imported XML, but it seems strange that there isn't anywhere to set this default permanently.
The behaviour of asXML() also seems to vary when printing part of a SimpleXML object (where it uses UTF-8) rather than the whole document (where it uses ISO 8859-1).
Adding
putenv('LANG=en_GB.UTF-8');
setlocale(LC_ALL, 'en_GB.UTF-8');
to the script doesn't seem to help.
Reproduce code:
---------------
// manually set encoding to UTF-8
$doc = simplexml_load_string('<?xml version="1.0" encoding="UTF-8"?><text>umlaut ? here</text>');
print $doc->asXML() . "\n";
// defaults to UTF-8
$doc = simplexml_load_string('<doc><text>umlaut ? here</text></doc>');
print $doc->text->asXML() . "\n\n";
// defaults to ISO 8859-1
$doc = simplexml_load_string('<text>umlaut ? here</text>');
print $doc->asXML() . "\n";
Expected result:
----------------
<?xml version="1.0" encoding="UTF-8"?>
<text>umlaut ? here</text>
<text>umlaut ? here</text>
<?xml version="1.0"?>
<text>umlaut ? here</text>
Actual result:
--------------
<?xml version="1.0" encoding="UTF-8"?>
<text>umlaut ? here</text>
<text>umlaut ? here</text>
<?xml version="1.0"?>
<text>umlaut ü here</text>
PatchesPull RequestsHistoryAllCommentsChangesGit/SVN commits
|
|||||||||||||||||||||||||||
Copyright © 2001-2025 The PHP GroupAll rights reserved. |
Last updated: Sat Nov 01 00:00:01 2025 UTC |
I've changed the title, as I found that using DOM works the same way: === $dom = new DOMDocument(); $dom->loadXML('<?xml version="1.0" encoding="UTF-8"?><text>?</text>'); print $dom->saveXML() . "\n"; // UTF-8 $dom->loadXML('<?xml version="1.0"?><text>?</text>'); print $dom->saveXML() . "\n"; // not UTF-8 print $dom->saveXML($dom->firstChild) . "\n"; // UTF-8 === Maybe it is supposed to work this way, but it's unintuitive and it would be useful to know why.