tags:

views:

228

answers:

3

How to Change innerHTML of a php DOMElement ?

A: 

Have a look at this library PHP Simple HTML DOM Parser http://simplehtmldom.sourceforge.net/

It looks pretty straightforward. You can change innertextproperty of your elements. It might help.

Jull
PHP, not JavaScript... PHP's implementation of DOM does not have an `innerHTML` property.
musicfreak
yes, my fault. but php5 HTML DOM parser has 'innertext'. http://simplehtmldom.sourceforge.net/
Jull
That's not the library the OP was referring to. See: http://php.net/manual/en/book.dom.php But you could edit your answer and link to the library you found and see if the OP wants to switch.
musicfreak
+1  A: 

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->insertBefore($newElement, $el);
    $el->parentNode->replaceChild($el);

    return $newElement);
}

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

Michael T. Smith
+1  A: 

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"&gt;FF&lt;/a&gt;';

// print document (with our changes)
echo $doc->saveXML();
?>
Keyvan