PHP domDocument to remove child nodes of a child node

后端 未结 1 562
礼貌的吻别
礼貌的吻别 2021-01-21 15:33

How do I remove a parent node of a child node, but keep all the children?

The XML file is this:





        
相关标签:
1条回答
  • 2021-01-21 15:50

    A good approach to process XML data is to use the DOM facility.

    It's quite easy once you get introduced to it. For example:

    <?php
    
    // load up your XML
    $xml = new DOMDocument;
    $xml->load('input.xml');
    
    // Find all elements you want to replace. Since your data is really simple,
    // you can do this without much ado. Otherwise you could read up on XPath.
    // See http://www.php.net/manual/en/class.domxpath.php
    $elements = $xml->getElementsByTagName('category');
    
    // WARNING: $elements is a "live" list -- it's going to reflect the structure
    // of the document even as we are modifying it! For this reason, it's
    // important to write the loop in a way that makes it work correctly in the
    // presence of such "live updates".
    while($elements->length) {
        $category = $elements->item(0); 
        $name = $category->firstChild; // implied by the structure of your XML 
    
        // replace the category with just the name 
        $category->parentNode->replaceChild($name, $category); 
    } 
    
    // final result:
    $result = $xml->saveXML();
    

    See it in action.

    0 讨论(0)
提交回复
热议问题