Simplify / format output in SimpleXML

I have this simplexml script that I use to send 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 appears, 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 tried the method found HERE and THIS IS GOOD , but do not format the XML correctly in strings, as they should look like

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

In the first link, I even changed loadXMLto loadbecause it loadXMLexpects a string as XML. Can someone help me find a solution to this?

+3
source share
3 answers

AFAIK simpleXML cannot do this on its own.

However, a DOMDocument can.

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

, stackoverflow . : [ : undefined DOMElement:: saveXML() , $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"); 

+2

this code worked for me and it is also pretty clean:

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

echo $xml->asXML();

where $ xml is SimpleXMLElement - this code will print the XML as follows

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

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

Hope this helps you!

0
source

All Articles