这是我正在处理的 XML 文件:
<list>
<activity>swimming</activity>
<activity>running</activity>
<activity>soccer</activity>
</list>
index.php,显示带有复选框的活动列表的页面,删除选中活动的按钮和添加新活动的字段:
<html>
<head></head>
<body>
<?php
$xmldoc = new DOMDocument();
$xmldoc->load('sample.xml', LIBXML_NOBLANKS);
$count = 0;
$activities = $xmldoc->firstChild->firstChild;
//prints the list of activities, with checkboxes on the left for each item
//the $count variable is the id to each entry
if($activities!=null){
echo '<form name=\'erase\' action=\'delete.php\' method=\'post\'>' . "\n";
while($activities!=null){
$count++;
echo " <input type=\"checkbox\" name=\"activity[]\" value=\"$count\"/>";
echo ' '.$activities->textContent.'<br/>'."\n";
$activities = $activities->nextSibling;
}
echo ' <input type=\'submit\' value=\'erase selected\'>';
echo '</form>';
}
?>
//section used for inserting new entries. this feature is working as expected.
<form name='input' action='insert.php' method='post'>
insert activity:
<input type='text name='activity'/>
<input type='submit' value='send'/>
<br/>
</form>
</body>
</html>
delete.php,它没有按预期工作:
<?php
$xmldoc = new DOMDocument();
$xmldoc->load('sample.xml', LIBXML_NOBLANKS);
$atvID = $_POST['activity'];
foreach($atvID as $id){
$delnode = $xmldoc->getElementsByTagName('activity');
$xmldoc->firstChild->removeChild($delnode->item($id));
}
$xmldoc->save('sample.xml');
?>
我已经使用硬编码的任意 id 测试了没有循环的删除例程,并且它有效。我还测试了 $atvID 数组,它正确打印了选定的 ID 号。当它在循环内时,它输出的错误如下:
可捕获的致命错误:传递给 DOMNode::removeChild() 的参数 1 必须是 DOMNode 的实例,在第 9 行的 /directorypath/delete.php 中给出了 null
我的代码有什么问题?