PHP - DOMDocument - need to modify / replace the existing HTML tag w / new

I am trying to change all the <P> tags in a document to <DIV> . This is what I came up with, but it doesn't seem to work:

 $dom = new DOMDocument; $dom->loadHTML($htmlfile_data); foreach( $dom->getElementsByTagName("p") as $pnode ) { $divnode->createElement("div"); $divnode->nodeValue = $pnode->nodeValue; $pnode->appendChild($divnode); $pnode->parentNode->removeChild($pnode); } 

This is the result I want:

Before:

 <p>Some text here</p> 

After:

 <div>Some text here</div> 
+7
source share
2 answers

You add a div to your p , which leads to <p><div></div></p> , removing p will remove everything.
In addition, $divnode->createElement() will not work if $divnode not initialized.

Try using DOMDocument :: replaceChild () instead (the position of the div in dom will be the same as p c).

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

Extended 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; } 
0
source

All Articles