正在格式化输出文件的XML


Formatting XML for output file

我的代码可以输出基于HTML表单的XML文件,但输出格式只是一个长字符串,如下所示:

<?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>

而不是这个:

<?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>

我正在使用formatOutput = truepreserveWhiteSpace = false,但它不起作用。这是我的代码:

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'); 
}

请改用saveXML()方法。

更新:

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

更新2:

请参阅手册,特别是devin的评论。他说你应该把preserveWhitespace放在load之前(正如Rolando Isidoro给出的链接也指出的那样)。

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