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:
Argu开发者_JAVA技巧ment 1 passed to DOMNode::removeChild() must be an instance of DOMNode, null given in delUser.php
XML file:
<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
. You do not have a schema or DTD attached, so the id attribute is not a valid ID attribute in the XML sense. Thus, it cannot be found by getElementById
. In addition, IDs may not start with a digit.
Either use XPath, e.g.
$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.
Once you fetched the node, the easiest way to remove it is to fetch the parentNode
from it, e.g.
$node->parentNode->removeChild($node);
Further details in Simplify PHP DOM XML parsing - how?
getElementByID()
take a string as parameter as shown on the manual.
So it should be $id="101";
Plus, you should have a check before using removeChild()
like if(!is_null($user)){...}
@Gordon's solution is faster but if you don't understand XPATH (which you should learn), you can use this :
$users = $doc->getElementsByTagName('user');
foreach($users as $user){
if($user->hasAttribute('id') && $user->getAttribute('id') == $id){
$user->parentNode->removeChild($user);
}
}
DEMO HERE
精彩评论