Php - Domdocument - Need To Change/replace An Existing Html Tag W/ A New One
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: $dom = new DOMDocument; $dom->loadHTML($htmlf
Solution 1:
You are appending the div
to your p
which results in <p><div></div></p>
, 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 div
s position in the dom will be the same as the p
s).
foreach( $dom->getElementsByTagName("p") as$pnode ) {
$divnode = $dom->createElement("div", $pnode->nodeValue);
$dom->replaceChild($divnode, $pnode);
}
Solution 2:
Enhanced function from this answer
functionchangeTagName($node, $name) {
$childnodes = array();
foreach ( $node->childNodes as$child ) {
$childnodes[] = $child;
}
$newnode = $node->ownerDocument->createElement( $name );
foreach ( $childnodesas$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;
}
Post a Comment for "Php - Domdocument - Need To Change/replace An Existing Html Tag W/ A New One"