I'm start to learn how to use the domDocument
and SimpleXML
classes to create and parse xml in PHP.
When reading through the domDocument
class definition, I see a property for formatOutput that says it:
Nicely formats output with indentation and extra space.
I added some example code and set formatOutput
to true:
<?php
try{
$dom = new domDocument("1.0");
$dom->preserveWhiteSpace = false;
$dom->formatOutput = true;
$user = $dom->createElement("Users");
$root = $dom->appendChild($user);
$sxe = simplexml_import_dom($dom);
$user1 = $sxe->addChild('user');
$user1->addChild("firstname", "Billy");
$user1->addChild("lastname", "Anyteen");
$user1->addAttribute('role', 'student');
$user2 = $sxe->addChild('user');
$user2->addChild('firstname', 'Debbie');
$user2->addChild('lastname', 'Little');
$user2->addAttribute('role', 'teacher');
$xmlString = $sxe->saveXML();
echo $xmlString;
}catch (Exception $d){
echo $e->getMessage();
}
When I look at the output in either my browser's developer tools network tab or via command line php the output comes out inline:
Chrome Dev tools:
<?xml version="1.0"?>
<Users><user role="student"><firstname>Billy</firstname><lastname>Anyteen</lastname></user><user role="teacher"><firstname>Debbie</firstname><lastname>Little</lastname></user></Users>
Command line:
$ php index.php
<?xml version="1.0"?>
<Users><user role="student"><firstname>Billy</firstname><lastname>Anyteen</lastname></user><user role="teacher"><firstname>Debbie</firstname><lastname>Little</lastname></user></Users>
Is this the expected result? From the property description I would expect the output to look like this:
<?xml version="1.0"?>
<Users>
<user role="student">
<firstname>Billy</firstname>
<lastname>Anyteen</lastname>
</user>
<user role="teacher">
<firstname>Debbie</firstname>
<lastname>Little</lastname>
</user>
</Users>
If the formatOutput
property isn't the way I should be getting this kind of spacing and indenting, is there a way that I can get the output in that fashion? (I've seen the tag mentioned but it seems to be a depreciated tag).