Format output of $SimpleXML->asXML(); [duplicate]
Solution 1:
There's a variety of solutions in the comments on the PHP manual page for SimpleXMLElement. Not very efficient, but certainly terse, is a solution by Anonymous
$dom = dom_import_simplexml($simpleXml)->ownerDocument;
$dom->formatOutput = true;
echo $dom->saveXML();
The PHP manual page comments are often good sources for common needs, as long as you filter out the patently wrong stuff first.
Solution 2:
The above didn't work for me, I found this worked:
$dom = new DOMDocument("1.0");
$dom->preserveWhiteSpace = false;
$dom->formatOutput = true;
$dom->loadXML($simpleXml->asXML());
echo $dom->saveXML();
Solution 3:
Found a similar solution...to format raw xlm data..from my php SOAP
requests __getLastRequest & __getLastResponse
, for quick debugging the xml's i have combined it with google-code-prettify
.
Its a good solution if you want to format sensitive xml data and don't want to do it online.
Some sample code below, may be helpful to others:
$dom = new DOMDocument;
$dom->preserveWhiteSpace = false;
$dom->formatOutput = true;
$dom->loadXML($data); //=====$data has the raw xml data...you want to format
echo '<script src="https://cdn.rawgit.com/google/code-prettify/master/loader/run_prettify.js"></script>';
echo "<br/> <pre class=\"prettyprint\" >". htmlentities($dom->saveXML())."</pre>";
Below is a sample of the Formatted XML Output I got:
Note: The formatted XML is available in $dom->saveXML()
and can be directly saved to a xml file using php file write.