[英]Error while removing an element from XML via PHP functions
I am trying to Delete a user with particular ID from an xml file but facing following error: 我正在尝试从xml文件中删除具有特定ID的用户,但遇到以下错误:
Argument 1 passed to DOMNode::removeChild() must be an instance of DOMNode, null given in delUser.php
传递给DOMNode :: removeChild()的参数1必须是DOMNode的实例,在delUser.php中为null
XML file: XML档案:
<currentUsers>
<user id="101" firstName="Klashinkof" p2p="Yes" priority="Low"/>
<user id="102" firstName="John" p2p="Yes" priority="High"/>
</currentUsers>
code: 码:
<?php
$id=101; //Test
// SETUP $doc
$doc = new DomDocument("1.0");
$doc->preserveWhiteSpace = FALSE;
$doc->validateOnParse = true;
$doc->Load('currUsers.xml');
//REMOVE ID
$user= $doc->getElementByID($id);
$users= $doc->documentElement;
if ($oldPerson = $users->removeChild($user)) {
// worked
echo "DELETED user {$id}";
} else {
return "Couldn't remove $id listing";
}
$doc->save(curr.xml);
?>
Your 你的
$doc->getElementById($id);
returns NULL
. 返回
NULL
。 You do not have a schema or DTD attached, so the id attribute is not a valid ID attribute in the XML sense. 您没有附加架构或DTD,因此从XML的角度来看,id属性不是有效的ID属性。 Thus, it cannot be found by
getElementById
. 因此,无法通过
getElementById
找到它。 In addition, IDs may not start with a digit. 此外,ID不能以数字开头。
Either use XPath, eg 要么使用XPath,例如
$xp = new DOMXPath($doc);
$node = $xp->query("//*[@id='$id']")->item(0);
or change the id attribute to xml:id
, but then you will also have to use a valid ID attribute value. 或将id属性更改为
xml:id
,但是您还必须使用有效的ID属性值。
Once you fetched the node, the easiest way to remove it is to fetch the parentNode
from it, eg 提取节点后,最简单的删除方法是从节点获取
parentNode
,例如
$node->parentNode->removeChild($node);
Further details in Simplify PHP DOM XML parsing - how? 简化PHP DOM XML解析中的更多详细信息-如何?
getElementByID()
take a string as parameter as shown on the manual .getElementByID()
以字符串作为参数, 如手册中所示 。
So it should be $id="101";
因此应为 $id="101";
Plus, you should have a check before using removeChild()
like if(!is_null($user)){...}
另外,你应该在使用前检查 removeChild()
一样if(!is_null($user)){...}
@Gordon's solution is faster but if you don't understand XPATH (which you should learn), you can use this : @Gordon的解决方案速度更快,但是如果您不了解 XPATH(应学习的知识),则可以使用以下方法:
$users = $doc->getElementsByTagName('user');
foreach($users as $user){
if($user->hasAttribute('id') && $user->getAttribute('id') == $id){
$user->parentNode->removeChild($user);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.