取消设置xml子项不起作用

I have the xml file "flashcards.xml":

<flashcards>
 <category name="testCategory">
    <card front="A" back="B"/>
    <card front="C" back="D"/>
    <card front="E" back="F"/>
 </category>
</flashcards>

I try to remove a category by given attribute "name" like this in php:

<?php
  $xml = simplexml_load_file("flashcards.xml");
  if (isset($_POST['remCat'])) {
      $remCat = $_POST['remCat'];
      $path = 'category[@name="' . $remCat . "\"]";

      $allCategories = $xml->xpath($path);
      $toRemove = $allCategories[0];
      unset($xml->$toRemove);

      var_dump($xml->asxml());
  }
?>

This code should load the file, looks for the category child with the attribute "remCat" and unsets it. If I print out $toRemove its the right node, but var_dump($xml->asxml()); prints the unchanged file. The child is not removed.

Using unset in this case is difficult as your trying to use $xml->$toRemove. So your trying to use the SimpleXMLElement returned by XPath to remove the element in the original document. This would work if you wanted to unset($xml->category[0]); but not with a SimpleXMLElement.

You can instead use...

$allCategories = $xml->xpath($path);
echo $allCategories[0]->asXML().PHP_EOL;
$toRemove = $allCategories[0];
//unset($xml->$toRemove);
$dom=dom_import_simplexml($toRemove);
$dom->parentNode->removeChild($dom);

This uses the much more powerful DOM api.