-1

我的代码可以输出基于 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 = trueas well as 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'); 
}
4

1 回答 1

2

试试这个saveXML()方法。

更新:

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

更新 2:

请参阅手册,特别是 devin 的评论。他说你应该把它放在前面(因为链接 Rolando Isidoro 也给出了状态)preserveWhitespaceload

$doc = new DOMDocument('1.0');
$doc->preserveWhiteSpace = false;
$doc->load('data.xml');
$doc->formatOutput = true;
file_put_contents('test.xml', $doc->saveXML());
于 2013-07-12T17:02:01.677 回答