How do you rename a tag in SimpleXML through a DOM object?

后端 未结 4 515
隐瞒了意图╮
隐瞒了意图╮ 2020-12-02 00:51

The problem seems straightforward, but I\'m having trouble getting access to the tag name of a SimpleXMLElement.

Let\'s say I have the follow XML structure:

4条回答
  •  既然无缘
    2020-12-02 01:30

    Rather late but I came up with the fallowing solution by replacing the hell out of the xml. I thought this might help some people as I couldnt find any good solution on the web without copying all children.

    function RenameNode(SimpleXMLElement $Entire_XML, SimpleXMLElement $Node, $New_Title) 
    {    
        $Full_XML   = $Entire_XML->asXML();
        $Old_Title  = $Node->getName();
        $XML_String = $Node->asXML();
        $Replaced   = preg_replace("/$Old_Title/", $New_Title, $XML_String, 1);
    
        if (count($Node->children())>0) 
        {
            $Replaced = strrev(
                preg_replace(
                    strrev("/$Old_Title/"), 
                    strrev($New_Title), 
                    strrev($Replaced), 
                    1
                )
            );    
        }
    
        $Full_XML = str_replace($XML_String, $Replaced, $Full_XML);
    
        return simplexml_load_string($Full_XML);
    }
    

    Sidenote: This function can be simplified but I quickly rewrote this function in order to post this here. The original function I use looks a little bit different

提交回复
热议问题