已回答@ setAttribute not saving back to XML page
我的XML如下:
<?xml version="1.0" encoding="UTF-8"?>
<facilities>
<areas>
<area name="Rocket">
<trails>
<trail name="Trail 1" status="CLOSED" />
<trail name="Trail 2" status="CLOSED" />
<trail name="Trail 2" status="CLOSED" />
</trails>
</area>
</areas>
</facilities>
我可以使用以下代码成功编辑属性:
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<?php
$xml = new DOMDocument('1.0', 'utf-8');
$xml->formatOutput = true;
$xml->preserveWhiteSpace = false;
$xml->load('example.xml');
$xpath = new DOMXpath($xml);
$asstatus = $xpath->query("//facilities/areas/area[@name='Rocket']/trails/trail[@name='Trail 1']/@status")->item(0);
$childForm = '';
foreach ( $xpath->query("//trails/trail") as $trail ) {
$childForm .= "<form action=''>
<span class=\"title\">".$trail->getAttribute("name")."</span> <span class=\"title\">Status</span>
<select name=\"asstatusform\" >
<option selected value=".$trail->getAttribute("status").">".$trail->getAttribute("status")."</option>
<option value=\"OPEN\">OPEN</option>
<option value=\"CLOSED\">CLOSED</option>
<option value=\"RACING CLOSURE\">RACING CLOSURE</option>
</select></span>
<br>
</form>";
}
?>
<form action="" method="POST">
<?php echo $childForm; ?>
<input name="submit" type="submit" value="Save" />
</form>
<?php
if (isset($_POST['submit']))
{
$trail->setAttribute('status', $_POST['asstatusform']);
htmlentities($xml->save('example.xml'));
}
?>
我想知道是否有一种简单的方法可以将其更改为使用foreach,这样我就不必为每个单独的跟踪名称创建新的查询和表单。到目前为止,我已经尝试了几种变体,但是都没有成功。
答案 0 :(得分:0)
使用XPath提取路径列表,然后为每个路径获取显示属性的简单组合。
foreach ( $xpath->query("//trails/trail") as $trail ) {
echo $trail->getAttribute("name")."/".
$trail->getAttribute("status").PHP_EOL;
}
您可以决定如何显示此数据-单独的表格/表格等。
代码的输出从使用嵌入的PHP将数据回显到HTML切换。您需要保持一致,并确保您还正确地嵌套了引号。以下应该在循环中起作用...
echo "<form method=\"POST\" action=''>
<span class=\"title\">".$trail->getAttribute("name")."</span> <span class=\"title\">Status</span>
<select name=\"asstatusform\" >
<option selected value=".$trail->getAttribute("status").">".$trail->getAttribute("status")."</option>
<option value=\"OPEN\">OPEN</option>
<option value=\"CLOSED\">CLOSED</option>
<option value=\"RACING CLOSURE\">RACING CLOSURE</option>
</select></span>
<br>
<input name=\"submit\" type=\"submit\" value=\"Save\" />
</form>";