7

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>
1

2 Answers 2

9

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);
}
Sign up to request clarification or add additional context in comments.

4 Comments

One note: if $pnode->nodeValue is not a plain text, but has extra nodes in it, only text will be left (html will be stripped).
You can't just replace items while iterating since the index changes and you end up with weird results.
guess what: I actually tested this at the time I answered it. So in case you use a recent PHP version foreach can handle the manipulation of the index.
as Sanne said their will be an error for multiple items. Check this answer stackoverflow.com/questions/12018747/…
0

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;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.