php - 使用 PHP DOM 删除 XML 元素的问题

标签 php xml dom

这是我正在处理的 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 编号。当它在循环内时,这是它输出的错误:

Catchable fatal error: Argument 1 passed to DOMNode::removeChild() must be an instance of DOMNode, null given in /directorypath/delete.php on line 9

我的代码有什么问题吗?

最佳答案

DOMNodeList 项的索引从 0 开始; 您需要将 $count++ 移至输出步骤中 while 循环的末尾。

关于php - 使用 PHP DOM 删除 XML 元素的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/195764/

相关文章:

php - PHP 5.3 中的 MessageFormatter 类有什么用?

php - 使用 SQL 更新了 1 列中的 2 个值

xml - 使用 xmlstarlet 或 xmllint 获取属性值

php - 通过 PHP/MySQL 将应用程序数据导出为 XML 的最佳实践?

php - 如何将链接显示为 md5 而不是普通链接

php - mysql查询执行倒计时

xml - 如何将文字和变量放入标签中?

jquery - 如何创建一个空的、非空的 jQuery 对象以供追加?

javascript - 如何针对任何标题稳健地解析文档并构建仅包含这些标题的 <ul> 树

javascript - 使用 javascript 插入具有冲突 ID 的 SVG