How can I change the name of an element in DOM?

后端 未结 3 1617
感情败类
感情败类 2020-12-01 18:53

In PHP with DOM, I have a DomElement object which represents an element.

I have one case where I need to change this so its element name is

3条回答
  •  悲&欢浪女
    2020-12-01 19:44

    Thanks to your post, I could quickly solve the same issue for me. However, I had a DOM_NOT_FOUND exception. This is probably a PHP Version issue, since the original post is 5 years old.

    According to the PHP Documentation (Feb 2014)

    DOM_NOT_FOUND
      Raised if oldnode is not a child of this node. 
    

    So, I have replaced

    $newnode->ownerDocument->replaceChild($newnode, $node);
    

    with

    $node->parentNode->replaceChild($newnode, $node);
    

    Here is the complete function (tested):

    public static function changeTagName($node, $name) {
        $childnodes = array();
        foreach ($node->childNodes as $child){
            $childnodes[] = $child;
        }
        $newnode = $node->ownerDocument->createElement($name);
        foreach ($childnodes as $child){
            $child2 = $node->ownerDocument->importNode($child, true);
            $newnode->appendChild($child2);
        }
        foreach ($node->attributes as $attrName => $attrNode) {
            $attrName = $attrNode->nodeName;
            $attrValue = $attrNode->nodeValue;
            $newnode->setAttribute($attrName, $attrValue);
        }
        $node->parentNode->replaceChild($newnode, $node);
        return $newnode;
    }
    

    It is also worth mentioning that when you want to use this function, you should traverse the DOM Tree in reversed order as explained in other posts.

    UPDATE: After months of using and updating to PHP Version 5.5.15 on windows, I had an error saying $attr could not be converted to a string. So I updated third for-each loop above.

提交回复
热议问题