PHP 如何从 DOMDocument 读取 XML 编码

PHP How to read XML encoding from DOMDocument

我正在使用 PHPs DOMDocument 以可读格式输出 XML 文档。我想通过在响应头中设置字符编码来告诉浏览器文档是如何编码的。 XML 声明如下:<?xml version="1.0" encoding="ISO-8859-1"?> 这是我的代码:

$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();

我找不到使用 $dom (DOMDocument) 中的方法从 XML 中获取编码 "ISO-8859-1" 的方法。我知道我可以用正则表达式来获取它,但不是有类似从 DOMDocument 对象获取编码属性的东西吗? $dom->getAttribute('encoding') 没用。

我正在搜索一些复杂的东西,但实际上很简单:$encoding = $dom->encoding