我正在尝试将HTML表单的结果保存到XML文件中以供以后处理。表单很遗憾,看起来我一次只能保存一个答案,但我想在XML文件中写下所有答案。这是我试过的:
<?php
if(isset($_POST['submit']))
{
$mileage = $_POST['form'];
$file = fopen("data.xml","r+");
fwrite($file,$mileage);
fclose($file);
print_r(error_get_last());
}
?>
<form action= "" method="post" name="form">
<input type="hidden" value = "<?xml version='1.0' encoding='UTF-8'?>"/>
<input type="hidden" value="<miles>"/>
<span class="XMLsimpleType" onclick="selectelm(this, event);" ondblclick="selectelm(this, event);">
<label>Car: </label>
<input type="text" class="car" name="car" value="" onfocus="focusGained(this)" onchange="textChanged(this)" /></span>
<br/></span>
<br>
<span class="XMLsimpleType" onclick="selectelm(this, event);" ondblclick="selectelm(this, event);">
<span class="bike">
<label>Bike: </label>
<input type="text" class="bike" name="bike" value="" onfocus="focusGained(this)" onchange="textChanged(this)" /></span>
<br/></span>
<br>
<input type="hidden" value="</miles>"/>
<input type="submit" name="submit" value="submit"><br>
</form>
表单应该创建一个格式正确的简单XML文件,如下所示:
<?xml version='1.0' encoding='UTF-8'?>
<miles>
<car>123</car>
<bike>245</bike>
</miles>
我花了四个小时来看这个,我知道我可以让它更简单,但首先我想让它运转起来。我可以编写单个表单条目,但不能写整个表单和XML信息。我做错了什么?
答案 0 :(得分:0)
这应该可行(我已将表单和处理拆分为两个单独的文件):
yourform.php(简体):
<form action='showXML.php' method='POST'>
car <input type='text' name='car'>
<br />
bike <input type='text' name='bike'>
<input type='submit' name='submit' value='submit'>
</form>
showXML.php:
<?php
if(isset($_POST['submit']))
{
$xml = new SimpleXMLElement("<?xml version=\"1.0\" encoding=\"utf-8\" ?><miles></miles>");
$xml->addChild('car', $_POST['car']);
$xml->addChild('bike', $_POST['bike']);
$asXML = $xml->asXML();
$file = fopen("data.xml","w+");
fwrite($file,$asXML);
fclose($file);
print_r(error_get_last());
if(file_exists('./data.xml'))
{
$myXML = file_get_contents('./data.xml');
$xml = new SimpleXMLElement($myXML);
$xmlpretty = $xml->asXML();
// pretty print the XML in browser
header('content-type: text/xml');
echo $xmlpretty;
}
}
?>