Search code examples
phpxmldompretty-print

Formatting SimpleXMLElement


According to this answer it is possible to echo out formatted xml. Yet this php code:

$xml = new SimpleXMLElement("<?xml version=\"1.0\" encoding=\"utf-8\" ?><data></data>");
$xml->addChild("child1", "value1");
$xml->addChild("child2", "value2");

$dom = new DOMDocument('1.0');
$dom->preserveWhiteSpace = false;
$dom->formatOutput = true;
$dom->loadXML($xml->asXML());
echo $dom->saveXML();

outputs value1 value2

So how do I format it correctly nowadays?


Solution

  • To echo out formatted XML (or HTML) you have to use htmlentities built-in function, that “convert all applicable characters to HTML entities”.

    In your case:

    echo htmlentities($dom->saveXML());
    

    will output this:

    <?xml version="1.0" encoding="utf-8"?> <data> <child1>value1</child1> <child2>value2</child2> </data>
    

    Using-it together with <pre> html tag, also newlines and spaces will be printed:

    echo '<pre>' . htmlentities($dom->saveXML()) . '</pre>';
    

    will output this:

    <?xml version="1.0" encoding="utf-8"?>
    <data>
        <child1>value1</child1>
        <child2>value2</child2>
    </data>