Prettifying/Formatting output in SimpleXML

点点圈 提交于 2019-12-05 23:15:36

AFAIK simpleXML can't do it on its own.

However, DOMDocument can.

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

i think above accepted answer from stackoverflow authority did not solved above question. Ref : [ I tried your answer and i received a Fatal error: Call to undefined method DOMElement::saveXML() on the line where the $formatted = $dom->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"); 

this code worked for me and it's also pretty clean:

header('Content-type: text/xml');

echo $xml->asXML();

where $xml is a SimpleXMLElement - this code will print the XML in the following way

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

This is taken from the official PHP documentation SimpleXMLElement::asXML

Hope this will help you!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!