Search code examples
phpxmlcharacter-encodingdomdocument

PHP How to read XML encoding from DOMDocument


I'm using PHPs DOMDocument to output an XML document in a readable format. I want to tell the browser, by setting the character encoding in the response header, how the document is encoded. The XML is declared like this: <?xml version="1.0" encoding="ISO-8859-1"?> This is my code:

$dom = new \DOMDocument;
$dom->preserveWhiteSpace = false;
$dom->formatOutput = true;
$loaded = $dom->loadXML($xml_string);
$encoding = $dom->getAttribute('encoding'); //This doesn't work
echo $dom->saveXML();

I couldn't find a way to get the encoding "ISO-8859-1" from the XML with a method from $dom (DOMDocument). I know I can get it with a regex, but isn't there something like getting the encoding attribute from the DOMDocument object? $dom->getAttribute('encoding') didn't work.


Solution

  • I was searching for something complex, when it was actually pretty simple: $encoding = $dom->encoding.