【发布时间】:2013-07-11 22:31:19
【问题描述】:
我正在尝试提出一个将表单数据导出为 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 文件中的根节点?
非常感谢您的帮助 - 乔
【问题讨论】:
-
该代码中的哪一行引发了 HTTP 500 错误?你能有你的表格代码吗?这将有助于我们帮助您。
-
添加了表单代码,虽然我不认为它应该有所作为。到目前为止,看起来问题(或更可能是第一个问题)在于: $theNode = $doc->createElement($headers[$i]);
-
A 500 Internal Sever Error 是总是查看服务器错误日志的邀请。它包含更多信息。由于这是 PHP,也很有可能是由于 PHP 中的致命错误,因此确保启用 PHP 错误日志并查看 PHP 错误日志也非常有用。 More about the 500 Internal Server Error
-
这个问题似乎是题外话,因为它是关于 500 内部服务器错误而没有显示相关日志文件。
标签: php xml domdocument