Remove a child with a specific attribute, in SimpleXML for PHP

后端 未结 17 2574
星月不相逢
星月不相逢 2020-11-22 02:50

I have several identical elements with different attributes that I\'m accessing with SimpleXML:


    
    

        
17条回答
  •  星月不相逢
    2020-11-22 02:52

    There is a way to remove a child element via SimpleXml. The code looks for a element, and does nothing. Otherwise it adds the element to a string. It then writes out the string to a file. Also note that the code saves a backup before overwriting the original file.

    $username = $_GET['delete_account'];
    echo "DELETING: ".$username;
    $xml = simplexml_load_file("users.xml");
    
    $str = "
    ";
    foreach($xml->children() as $child){
      if($child->getName() == "user") {
          if($username == $child['name']) {
            continue;
        } else {
            $str = $str.$child->asXML();
        }
      }
    }
    $str = $str."
    ";
    echo $str;
    
    $xml->asXML("users_backup.xml");
    $myFile = "users.xml";
    $fh = fopen($myFile, 'w') or die("can't open file");
    fwrite($fh, $str);
    fclose($fh);
    

提交回复
热议问题