我正在尝试提出一个将表单数据导出为 XML 格式的通用例程。目标是使其足够通用,以使表单元素 ID 用作 XML 节点,而表单值显然是节点内容。这是我到目前为止所拥有的:
if(isset($_POST['submit'])) {
$doc = new DOMDocument('1.0');
$doc->formatOutput = true;
$post = $_POST;
unset($post['submit']);
$data = array_values($post);
$headers = array_keys($post);
/* TODO - wrap next two lines with if clause */
/* to check for existing root node */
$root = $doc->createElement('student');
$root = $doc->appendChild($root);
for ($i = 0; count($headers) - 1; $i++) {
/* Create and append node for each form element to root */
$theNode = $doc->createElement($headers[$i]);
$theNode = $root->appendChild($theNode);
/* Add content to node */
$theValue = $doc->createTextNode($data[$i]);
$theValue = $theNode->appendChild($theValue);
}
$fh = fopen($file, 'w') or die("Can't open the XML file.");
fwrite($fh, $doc->saveXML());
fclose($fh);
header('Location: thanks.php');
}
而且,根据要求,这是表单代码,尽管我认为这无关紧要:
<form name="form1" method="post" action="">
<p>
<label for="name">Name: </label>
<input type="text" name="name" id="name" placeholder="Your full name" autofocus required>
</p>
<p>
<label for="email">Email: </label>
<input type="email" name="email" id="email">
</p>
<p>
<label for="cell">Cell: </label>
<input type="tel" name="cell" id="cell">
</p>
<p>
<label for="dob">Date of birth: </label>
<input type="date" name="dob" id="dob">
</p>
<p>
<label for="study">Years of art study: </label>
0 <input type="range" name="study" id="study" min="0" max="16"> 16
</p>
<p style="text-align: center;">
<input type="submit" name="submit" id="submit" value="Submit">
</p>
</form>
不幸的是,此代码导致 HTTP 错误 500。关于我做错了什么有什么想法吗?
哦,正如 TODO 所指出的,我还需要确定文件中是否已经存在数据(存在根节点),只需追加并且不要重新插入根节点。如何测试 XML 文件中的根节点?
非常感谢您的帮助 - 乔