为什么 DomDocument loadXML 对我不起作用?

Why is DomDocument loadXML not working for me?

我有一个非常简单的测试用例,我正在斗鸡眼试图找出我做错了什么。这是测试用例:

<?php
$xml = <<<XML
<?xml version="1.0"?>
<Contact>
    <Name>Foo Bar</Name>
    <Numbers>
        <Number>9876543210</Number>
        <Number>9876543212</Number>
    </Numbers>
    <Address>
        <Premise>11</Premise>
        <Postcode>ZZ99 9ZZ</Postcode>
    </Address>
</Contact>
XML;

$dom = new domDocument( '1.0', 'utf-8' );
$dom->preserveWhiteSpace = false;
$dom->formatOutput = true;
$dom->recover = true;
libxml_use_internal_errors(true);
$result = $dom->loadXML($xml);
print_r($result);
$errors = libxml_get_errors();
print_r($errors);
$dom->saveXML($xmlContentFormatted);
echo "<pre lang=xml>";
echo $xmlContentFormatted;
echo "</pre><br><br>";  
?>

并且输出:

1Array ( )

您的代码中存在一些错误,使用了未在任何地方定义的 $doc - 应该是 $dom,您尝试使用 saveXML 输出文档也是无效的.它试图将 $xmlContentFormatted 用作保存的上下文节点 - 同样 $xmlContentFormatted 未在任何地方定义 - 相反,您只需使用 saveXML() 的 return 值作为输出...

$dom = new DOMDocument( '1.0', 'utf-8' );
$dom->preserveWhiteSpace = false;
$dom->formatOutput = true;
$dom->recover = true;
libxml_use_internal_errors(true);
$dom->loadXML($xml);
echo "<pre lang=xml>";
echo $dom->saveXML();
echo "</pre><br><br>";