所以我有一个显示XML文件数据的网页。然而,我有一个表格,以及理想情况下应该能够改变数据。我认为实现这一目标的最佳方法是使用PHP中的Fopen函数并编辑特定的文本行。字符串不会很长,最多4个单词。我该如何使用fopen和一系列打开,读取和写入文件的函数来找到一行代码并替换它?
我认为你应该这样做:
-
将HTML中的输入标签的名称与XML中的节点相匹配(这只是一个让您的代码更有组织的建议)
-
当您将数据发送回服务器时,在Php代码中,使用SimpleXML您可以执行以下操作
给出以下XML文件
<root>
<config id="1">
<name>old name</name>
<category>old category</category>
</config>
<config id="2">
<name>old name</name>
<category>old category</category>
</config>
</root>
//Load the XML file
$xml = simplexml_load_file('PATH TO YOUR XML FILE');
//Update the values that you want to update
foreach($xml->root->config as $configGroup)
{
//Set the $IdToUpdate variable with the Id of the group that you want to update.
if ($configGroup['id'] == $IdToUpdate)
{
$configGroup->name = $_POST['name' . $IdToUpdate];//Your html must have the proper input names.
break;
}
}
//Save the changes
$xml->asXml('PATH TO YOUR XML FILE');
希望能有所帮助
你可能想从这里开始:http://www.php.net/manual/en/refs.xml.php
听起来你需要做几件事。
i)解析xml为对象或数组。
ii)找到你想要更新的元素
好吧,我的问题的答案很简单。如果您像我一样,基本上是PHP编程的新手,那么函数之类的东西可能会变得非常棘手,至少对我来说是这样。当您使用来自XML的数据时,每个标记实际上都变成了一个数组。
<configure id="firstblock">
<name>Name</name>
<category>Old</category>
</configure>
<configure id="second block">
<name>Name2</name>
<category>New</category>
</configure>
注意configure的行为就像一个数组。
$xml = SimpleXML_load_file('location of xml file here');
$xml->configure[0]->color = $_POST['name1'];
$xml->configure[0]->category = $_POST['category'];
$xml->configure[1]->name =$_POST['name2'];
$xml->configure[1]->category =$_POST['category2'];
$xml->asXml('location of xml file here');