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

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

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


    
    

        
17条回答
  •  星月不相逢
    2020-11-22 03:15

    I believe Stefan's answer is right on. If you want to remove only one node (rather than all matching nodes), here is another example:

    //Load XML from file (or it could come from a POST, etc.)
    $xml = simplexml_load_file('fileName.xml');
    
    //Use XPath to find target node for removal
    $target = $xml->xpath("//seg[@id=$uniqueIdToDelete]");
    
    //If target does not exist (already deleted by someone/thing else), halt
    if(!$target)
    return; //Returns null
    
    //Import simpleXml reference into Dom & do removal (removal occurs in simpleXML object)
    $domRef = dom_import_simplexml($target[0]); //Select position 0 in XPath array
    $domRef->parentNode->removeChild($domRef);
    
    //Format XML to save indented tree rather than one line and save
    $dom = new DOMDocument('1.0');
    $dom->preserveWhiteSpace = false;
    $dom->formatOutput = true;
    $dom->loadXML($xml->asXML());
    $dom->save('fileName.xml');
    

    Note that sections Load XML... (first) and Format XML... (last) could be replaced with different code depending on where your XML data comes from and what you want to do with the output; it is the sections in between that find a node and remove it.

    In addition, the if statement is only there to ensure that the target node exists before trying to move it. You could choose different ways to handle or ignore this case.

提交回复
热议问题