Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

html

dom

php

I'm trying to change all <P> tags in a document to <DIV>. This is what I've come 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>
like image 637
James Nine Avatar asked Jan 28 '11 03:01

James Nine


1 Answers

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 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);
}
like image 121
Samuel Herzog Avatar answered Sep 18 '22 18:09

Samuel Herzog