-1

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'); 
}
Cœur
  • 37,241
  • 25
  • 195
  • 267
Joe Lowery
  • 562
  • 11
  • 26

1 Answers1

2

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());
pritaeas
  • 2,073
  • 5
  • 34
  • 51
  • Could you be more explicit? I tried adding `$doc = saveXML();` prior to saving it as a file, but no go. – Joe Lowery Jul 12 '13 at 17:21
  • I've also tried $test1 = $doc->saveXML(); - but again, no love. What am I doing wrong? – Joe Lowery Jul 12 '13 at 18:37
  • saveXML outputs a string, you need to store and save that, for example with `file_put_contents()` – pritaeas Jul 12 '13 at 18:50
  • Still no love. It's saving the data, but not formatted. Any other ideas? – Joe Lowery Jul 12 '13 at 18:55
  • I ran it on my server, and outputs the XML formatted. No idea what's wrong. – pritaeas Jul 12 '13 at 19:08
  • Did you read Update 2? – pritaeas Jul 12 '13 at 19:16
  • And I did try moving the preserveWhitespace as well. What version of PHP are you running, Pritaeas? – Joe Lowery Jul 12 '13 at 19:19
  • Ah - I think I found the problem - Devin's comment further says "CAUTION: If your loaded xml file (test.xml) has an empty root node that is not shortened or has no children this will NOT work." And he's right. So, adding a comment does the trick. Whew! Thanks for hanging in there! Answer accepted and upvoted! – Joe Lowery Jul 12 '13 at 19:26