在 SimpleXML 中美化/格式化输出


Prettifying/Formatting output in SimpleXML

我有一个单形脚本,我正在使用这个 simplexml 脚本来发布从表单输入的数据。

$xml = simplexml_load_file("links.xml");
$sxe = new SimpleXMLElement($xml->asXML()); 
$person = $sxe->addChild("link");
$person->addChild("title", "Q: ".$x_title);
$person->addChild("url", "questions_layout.php#Question$id");
$sxe->asXML("links.xml"); 

当它出来时,它在一行上看起来像这样:

<link><title>Alabama State</title><url>questions_layout.php#Question37</url></link><link><title>Michigan State</title><url>questions_layout.php#Question37</url></link></pages>

但是我已经尝试了在这里找到的方法,但是两者都没有像这样正确格式化XML

的行
<link>
<title></title>
<url></url>
</link>

在第一个参考链接中,我什至将loadXML更改为load,因为loadXML期望字符串为XML。有人可以帮我找到解决这个问题的方法吗?

AFAIK simpleXML 无法单独完成。

但是,DOMDocument可以。

$dom = dom_import_simplexml($sxe)->ownerDocument;
$dom->formatOutput = TRUE;
$formatted = $dom->saveXML();

我认为上面接受的来自堆栈溢出权威的答案并没有解决上述问题。参考 : [ 我尝试了您的答案,但收到致命错误:在$formatted = $dom->saveXML();的行上调用未定义的方法 DOMElement::saveXML()

$simplexml = simplexml_load_file("links.xml");
$dom = new DOMDocument('1.0');
$dom->preserveWhiteSpace = false;
$dom->formatOutput = true;
$dom->loadXML($simplexml->asXML());
$xml = new SimpleXMLElement($dom->saveXML());
$person = $xml->addChild("link");
$person->addChild("title", "Q: ".$x_title);
$person->addChild("url", "questions_layout.php#Question$id");
$xml->saveXML("links.xml"); 

这段代码对我有用,而且也很干净:

header('Content-type: text/xml');
echo $xml->asXML();

其中$xml是 SimpleXMLElement - 此代码将按以下方式打印 XML

<Attribute>
   <ChildAttribute>Value</ChildAttribute>
</Attribute>

这取自官方PHP文档SimpleXMLElement::asXML

希望这对您有所帮助!