solvit.io

Pretty format the XML contents generated with SimpleXML and PHP

XML documents created by SimpleXML are formatted as a single string of contents, without any white space or new line between nodes. If you need to format the XML contents, use the following trick.

Solution
function formatXml($simpleXMLElement)
{
    $xmlDocument = new DOMDocument('1.0');
    $xmlDocument->preserveWhiteSpace = false;
    $xmlDocument->formatOutput = true;
    $xmlDocument->loadXML($simpleXMLElement->asXML());

    return $xmlDocument->saveXML();
}
Example
$node1 = new SimpleXMLElement('<node1/>');
$node2 = $node1->addChild('node2');
$node3 = $node2->addChild('node3');

$xmlContent = $node1->asXML();
// $xmlContent is:
// <?xml version="1.0"?>\n
// <node1><node2><node3/></node2></node1>\n

$xmlContent = formatXml($node1);
// $xmlContent is:
// <?xml version="1.0"?>\n
// <node1>\n
//   <node2>\n
//     <node3/>\n
//   </node2>
// </node1>
Find more solutions about: , ,