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

前端 未结 2 394
醉话见心
醉话见心 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 13:01

    You are appending the div to your p which results in

    , removing the p will remove everything.
    Additionally $divnode->createElement() won't work when $divnode isn't initialized.

    Try instead to use the DOMDocument::replaceChild() (the divs position in the dom will be the same as the ps).

    foreach( $dom->getElementsByTagName("p") as $pnode ) {
        $divnode = $dom->createElement("div", $pnode->nodeValue);
        $dom->replaceChild($divnode, $pnode);
    }
    

提交回复
热议问题