Search code examples
phpxmldomdocument

Formatting XML for output file


I've got my code working to output an XML file based on an HTML form, but the output format is just a long string like this:

<?xml version="1.0"?>
<students>
<student><name>Joey Lowery</name><email>jlowery@idest.com</email><cell>555-555-5555</cell><dob>1999-03-31</dob><study>8</study></student></students>

rather than this:

<?xml version="1.0"?>
<students>
  <student>
    <name>Joey Lowery</name>
    <email>jlowery@idest.com</email>
    <cell>555-555-5555</cell>
    <dob>1999-03-31</dob>
   <study>8</study>
  </student>
</students>

I am using formatOutput = true as well as preserveWhiteSpace = false, but it's not working. Here's my code:

if(isset($_POST['submit'])) {
$file = "data.xml";
$userNode = 'student';

$doc = new DOMDocument('1.0');
$doc->load($file);
$doc->preserveWhiteSpace = true;   
$doc->formatOutput = true;

$root = $doc->documentElement; 

$post = $_POST;
unset($post['submit']);

$user = $doc->createElement($userNode);
$user = $root->appendChild($user);

foreach ($post as $key => $value) {
    $node = $doc->createElement($key, $value);
    $user->appendChild($node);
}
$doc->save($file) or die("Error");
header('Location: thanks.php'); 
}

Solution

  • Try the saveXML() method instead.

    Update:

    file_put_contents($file, $doc->saveXML());
    

    Update 2:

    See the manual, specifically the comment from devin. He states you should put preserveWhitespace BEFORE the load (as the link Rolando Isidoro gave also states).

    $doc = new DOMDocument('1.0');
    $doc->preserveWhiteSpace = false;
    $doc->load('data.xml');
    $doc->formatOutput = true;
    file_put_contents('test.xml', $doc->saveXML());