格式化输出文件的XML

时间:2013-07-12 16:56:24

标签: php xml domdocument

我的代码正在根据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 = true以及preserveWhiteSpace = 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'); 
}

1 个答案:

答案 0 :(得分:2)

请尝试使用saveXML()方法。

更新

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

更新2:

请参阅manual,特别是devin的评论。他声明你应该preserveWhitespace放在load之前(正如罗兰多·伊西多罗给出的那些链接一样)。

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