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