Rename an XML node using PHP

后端 未结 2 1307
自闭症患者
自闭症患者 2020-12-21 19:28

I\'m trying to figure out how to rename a node in XML using PHP?

I Have come this far:

$dom = new DOMDocument( \'1.0\' );
$dom->preserveWhiteSpace         


        
2条回答
  •  孤城傲影
    2020-12-21 19:41

    A Node's name ("data" or "invites" respectively) cannot be renamed via the DOM because the Node::nodeName property is read-only.

    You can create a new node named "invites", append it before the "data" node, move the children of "data" to the new "invites" node, remove the "data" node, and then output the tree to get your result.

    Example:

    preserveWhiteSpace = false;
        $dom->formatOutput = true;
    
    // Load the xml file.
        $dom->loadXML('
        
          
            
              jmansa
              1
            
            1
          
        ', LIBXML_NOBLANKS );
        $xpath = new DOMXPath($dom);
    
        // Convert  to .
        if ($dataNode = $xpath->query("/library/data")->item(0))
        {
        // Create the  node.
            $invitesNode = $dom->createElement('invites');
            $dataAttrs   = $dataNode->attributes;
            foreach ($dataAttrs as $dataAttr)
            {   $invitesNode->setAttributeNodeNS($dataAttr->cloneNode());   }
            $dom->documentElement->appendChild($invitesNode);
    
        // Move the  children over.
            if ($childNodes = $xpath->query("/library/data/*"))
            {
                foreach ($childNodes as $childNode)
                {   $invitesNode->appendChild($childNode);  }
            }
    
        // Remove .
            $dataNode->parentNode->removeChild($dataNode);
        }
    
    // Test the result.
        echo $dom->saveXML();
    ?>
    

提交回复
热议问题