Why PHP's SimpleXML works to disk but not to browser?
14:24 28 Nov 2025

I have a legacy application that requires XML files generated by my PHP code, but with ISO-8859-2 encoding. It does not process UTF-8. The PHP version I'm using is 8.3.27, and the DB behind is MSSQL.

When I'm generating the XML file with SimpleXML I added the line on the top. When I'm doing $xml->asXML('filename.xml') the content of the file seems to be correct ISO-8859-2 and all special characters are correct. But when I'm sending it to the browser with:

header('Content-type: text/xml; charset=iso-8859-2"');
header('Content-Disposition: inline');
echo $xml->asXML();

special characters are all wrong, and the browser is whining on them:

This page contains the following errors:

error on line 2 at column 53: Encoding error

Below is a rendering of the page up to the first error. The line and column specify the first appearance of a special character. I tested it in Edge, Chrome, and Firefox, and got the same result.

Now I thought it was an encoding problem of SimpleXML that it uses UTF-8 internally, so I tried to transform the string:

echo mb_convert_encoding($xml->asXML(), "iso-8859-2", "utf-8");

This means (according to PHP documentation) that convert UTF-8 -> ISO-8859-2. The result is surprising at best. The XML is now displayed, but all special characters have been replaced by "?".

Just for curiosity, I tried the conversion the other way around:

echo mb_convert_encoding($xml->asXML(), "utf-8", "iso-8859-2");

This means: convert ISO-8859-2 -> UTF-8. More surprisingly, the XML content is now correct, and all special characters are present. Now, somebody please try to explain to me what the heck is happening here? The XML on disk is correct, but the same XML in the browser is incorrect, even though I'm sending the correct headers. But if I transform the string to UTF-8 the browser is suddenly just fine with it...

php encoding utf-8 simplexml iso-8859-2