我有一个XML文件,我希望能够使用表单进行编辑。
student.xml
<students>
<student>
<name>Jane Doe</name>
<email>email@email.com</email>
<school>School Name</school>
<coach>Coach Name</coach>
</student>
</students>
基本上我的表单设置如下:
<form method="post">
<input name="name" id="name" type="text">
<input name="school" id="school" type="text">
<input name="coach" id="coach" type="text">
<br>
<input type="submit" name="submit" value="submit">
</form>
PHP代码:
<?php
if(isset($_POST['submit'])) {
$data=simplexml_load_file('student.xml');
$data->student->name=$_POST['name'];
$data->student->school=$_POST['school'];
$data->student->coach=$_POST['coach'];
$handle=fopen("student.xml","wb");
fwrite($handle,$data->asXML());
fclose($handle);
}
$data=simplexml_load_file('student.xml');
?>
如何使用表单在一个表单中编辑多个节点?现在它将所有节点更改为与第一个节点相同。
编辑:代码已更新。这一切似乎都在起作用。谢谢你的帮助。
答案 0 :(得分:1)
以下对我有用。
旁注: 但是,我不确定您为何使用$data->student->coach=$_POST['coach'];
代替$data->item->coach=$_POST['coach'];
(另请参阅脚注) - 重要。
<?php
if(isset($_POST['submit'])) {
$data=simplexml_load_file('student.xml');
$data->item->name=$_POST['name'];
$data->item->school=$_POST['school'];
$data->item->coach=$_POST['coach'];
$handle=fopen("student.xml","wb");
fwrite($handle,$data->asXML());
fclose($handle);
}
$data=simplexml_load_file('student.xml');
$welcome=$data->item->name;
$school=$data->item->school;
$coach=$data->item->coach;
?>
<?php
echo $welcome . " ";
echo $school . " ";
echo $coach . " ";
?>
<form method="post">
Coach name: <br>
<input type = "text" name = "coach"> Present value in file: <?php echo $coach; ?>
<br><br>
School name: <br>
<input type = "text" name = "school"> Present value in file: <?php echo $school; ?>
<br><br>
Name:
<br>
<textarea name = "name"><?php echo $welcome; ?></textarea>
<br>
<input type="submit" name="submit" value="submit">
</form>
生成(在使用不同的值编辑后):
<?xml version="1.0"?>
<welcome>
<item>
<name>name 1</name>
<school>St-Peter</school>
<coach>Robert</coach>
</item>
</welcome>
使用生成的不同值进行编辑:
<?xml version="1.0"?>
<welcome>
<item>
<name>name 2</name>
<school>St-Andrews</school>
<coach>George</coach>
</item>
</welcome>
<强>脚注:强>
为了使其正常工作,必须已存在具有以下结构的现有文件。
<welcome>
<item>
<name>A name</name>
<school>A school name</school>
<coach>A coach's name</coach>
</item>
</welcome>
答案 1 :(得分:0)
我注意到您正在使用<form action= method="post">
。必须更改为:
<form action="" method="post">
另外,如果要链接到文件,则必须类似于<form action="afile.html" method="post">
。