PHP - DOMDocument - need to change/replace an existing HTML tag w/ a new one

前端 未结 2 393
醉话见心
醉话见心 2020-12-30 12:33

I\'m trying to change all

tags in a document to

. This is what I\'ve come up with, but it doesn\'t seem to work:



        
2条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-30 12:51

    Enhanced function from this answer

    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);
        }
        if ( $node->hasAttributes() ) {
            foreach ( $node->attributes as $attr ) {
                $attrName = $attr->nodeName;
                $attrValue = $attr->nodeValue;
                $newnode->setAttribute($attrName, $attrValue);
            }
        }
        $node->parentNode->replaceChild( $newnode, $node );
        return $newnode;
    }
    

提交回复
热议问题