1

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?

Community
  • 1
  • 1
Madmenyo
  • 8,389
  • 7
  • 52
  • 99
  • :) add `
    ` or just look page source
    – splash58 Jan 30 '16 at 13:51
  • Where are you testing it? If from your browser, you see above output because the browser interprete the xml code. Check the page source! Your code works fine, I have tested it! – fusion3k Jan 30 '16 at 13:55
  • @splash58 Page source does get the result I am after. But I want it to output like that just on the page, not necessarily the colors though. `
    ` just puts the values below each other.
    – Madmenyo Jan 30 '16 at 13:55
  • @Menno Gouw https://eval.in/510254 – splash58 Jan 30 '16 at 13:56
  • @fusion3k Testing it on localhost. I know the code works, I'm sending the xml to an app but I want to see the xml in a browser as well (without using page source). – Madmenyo Jan 30 '16 at 13:57
  • 1
    You want see xml code in the standard html page? If yes, try `echo htmlentities($dom->saveXML());` **Better:** `echo '
    '.htmlentities($dom->saveXML()).'
    ';`
    – fusion3k Jan 30 '16 at 13:58
  • @fusion3k thanks, thats it. – Madmenyo Jan 30 '16 at 14:02

1 Answers1

2

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>
fusion3k
  • 11,568
  • 4
  • 25
  • 47