Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change innerHTML of a php DOMElement [duplicate]

Tags:

dom

php

How to Change innerHTML of a php DOMElement ?

like image 484
iavian Avatar asked May 06 '10 02:05

iavian


3 Answers

Another solution:

1) create new DOMDocumentFragment from the HTML string to be inserted; 2) remove old content of our element by deleting its child nodes; 3) append DOMDocumentFragment to our element.

function setInnerHTML($element, $html)
{
    $fragment = $element->ownerDocument->createDocumentFragment();
    $fragment->appendXML($html);
    while ($element->hasChildNodes())
        $element->removeChild($element->firstChild);
    $element->appendChild($fragment);
}

Alternatively, we can replace our element with its clean copy and then append DOMDocumentFragment to this clone.

function setInnerHTML($element, $html)
{
    $fragment = $element->ownerDocument->createDocumentFragment();
    $fragment->appendXML($html);
    $clone = $element->cloneNode(); // Get element copy without children
    $clone->appendChild($fragment);
    $element->parentNode->replaceChild($clone, $element);
}

Test:

$doc = new DOMDocument();
$doc->loadXML('<div><span style="color: green">Old HTML</span></div>');
$div = $doc->getElementsByTagName('div')->item(0);
echo $doc->saveHTML();

setInnerHTML($div, '<p style="color: red">New HTML</p>');
echo $doc->saveHTML();

// Output:
// <div><span style="color: green">Old HTML</span></div>
// <div><p style="color: red">New HTML</p></div>
like image 77
Guest Avatar answered Nov 14 '22 19:11

Guest


I needed to do this for a project recently and ended up with an extension to DOMElement: http://www.keyvan.net/2010/07/javascript-like-innerhtml-access-in-php/

Here's an example showing how it's used:

<?php
require_once 'JSLikeHTMLElement.php';
$doc = new DOMDocument();
$doc->registerNodeClass('DOMElement', 'JSLikeHTMLElement');
$doc->loadHTML('<div><p>Para 1</p><p>Para 2</p></div>');
$elem = $doc->getElementsByTagName('div')->item(0);

// print innerHTML
echo $elem->innerHTML; // prints '<p>Para 1</p><p>Para 2</p>'

// set innerHTML
$elem->innerHTML = '<a href="http://fivefilters.org">FF</a>';

// print document (with our changes)
echo $doc->saveXML();
?>
like image 31
Keyvan Avatar answered Nov 14 '22 20:11

Keyvan


I think the best thing you can do is come up with a function that will take the DOMElement that you want to change the InnerHTML of, copy it, and replace it.

In very rough PHP:

function replaceElement($el, $newInnerHTML) {
    $newElement = $myDomDocument->createElement($el->nodeName, $newInnerHTML);
    $el->parentNode->insertBefore($newElement, $el);
    $el->parentNode->removeChild($el);

    return $newElement;
}

This doesn't take into account attributes and nested structures, but I think this will get you on your way.

like image 2
Michael T. Smith Avatar answered Nov 14 '22 21:11

Michael T. Smith