I'm trying to come up with a general routine for exporting form data to an XML format. The goal would be to make it general enough that the form element IDs would serve as the XML nodes, and the form values would obviously be the node content. Here's what I have so far:
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');
}
And, as requested, here's the form code, although I think that's irrelevant:
<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>
Unfortunately, this code results with an HTTP Error 500. Any ideas on what I'm doing wrong?
Oh, and as the TODO notes, I need to also figure out if there already is data (a root node exists) in the file, just append and don't reinsert the root node. How do I test for a root node in an XML file?
Thanks so much for your help - Joe