在PHP中删除XML节点

    $xmldoc = new DOMDocument();
    $xmldoc->load('card.xml');
    $root   = $xmldoc->documentElement;
    $fnode  = $root->firstChild;
    // we retrieve the chapter and remove it from the book
    $items = $xmldoc->getElementsByTagName('card');
    foreach ($items as $item){
        $node = $item->getElementsByTagName('cardnumber')->item(0);
        if ($node->nodeValue == $this->cardnumber){
            $node->parentNode->removeChild($node);
            $xmldoc->saveXML();
        }
    }

Above is the code I used to delete the card node if the card number is match, below is my XML format. But if failed to remove the card. Can anyone help?

<root>
  <card>
    <cardnumber>12345</cardnumber>
    <name>Tan</name>
  </card>
  ....
</root>

The way you have removed the node is correct. But you to save it in an xml after saveXml() or you can just print the new xml and check for the update you have done. And also as per your logic save should be done after the loop. (i.e) as follows,

$xmldoc = new DOMDocument();
$xmldoc->load('card.xml');
$root   = $xmldoc->documentElement;
$fnode  = $root->firstChild;
// we retrieve the chapter and remove it from the book
$items = $xmldoc->getElementsByTagName('card');
foreach ($items as $item){
    $node = $item->getElementsByTagName('cardnumber')->item(0);
    if ($node->nodeValue == $this->cardnumber){
        $node->parentNode->removeChild($node);            
    }
}
$xmldoc->save('newXmlFile.xml');

(OR)

print $xmldoc->saveXML();

Delete <card> with id=2 with simplexml:

$xml = simplexml_load_string($x); // assume XML in $x
$i = count($xml) - 1; 

for ($i; $i >= 0; $i--) {   
    $card = $xml->card[$i];
    if ($card['id'] == "2") unset($xml->card[$i]);
}

see it working : http://codepad.viper-7.com/9cX1qR

$xmlDoc->getElementsByTagName("nameNode")->item(0)->parentNode
    ->removeChild($xmlDoc->getElementsByTagName("nameNode")->item(0));