Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prettifying/Formatting output in SimpleXML

I have this simplexml script i'm using to post data entered from a form.

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

and when it comes out it looks like this on one line:

<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>

But i've tried the method found HERE and THIS AS WELL but neither format the XML correctly in the lines as they should be like

<link>
<title></title>
<url></url>
</link>

In the first reference link I even changed loadXML to load, because loadXML expects a string as XML. Can somebody help me find a solution to this please?

like image 439
Tower Avatar asked Dec 05 '25 18:12

Tower


1 Answers

AFAIK simpleXML can't do it on its own.

However, DOMDocument can.

$dom = dom_import_simplexml($sxe)->ownerDocument;
$dom->formatOutput = TRUE;
$formatted = $dom->saveXML();
like image 178
alex Avatar answered Dec 08 '25 08:12

alex



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!