tags:

views:

184

answers:

2

Using PHP's DOM functions, how do you convert a DOM Node's contents into a string?

<foo>
    Blah blah <bar baz="1">bah</bar> blah blah
</foo>

Given foo as the current context node, how do you get 'Blah blah <bar baz="1">bah</bar> blah blah' as a string? Using $node->textContent or $node->nodeValue just returns the text nodes, not the <bar baz="1"> bits.

Basically, the equivalent of Javascript's innerHTML property...

+4  A: 

You can create a new DOMDocument from the <foo> node and parse it as XML or HTML:

function getInnerHTML($node) {
    $tmpDoc = new DOMDocument('1.0');
    $block = $tmpDoc->importNode($node->cloneNode(true),true);
    $tmpDoc->appendChild($block);
    $outer = $tmpDoc->saveHTML();
    //this will remove the outer tags
    return substr($outer,strpos($outer,'>')+1,-(strlen($node->nodeName)+4)); 
}
Freddy
Beat me to it by seconds. I've posted the SimpleXML way instead, though this is rather trivial.
Tomalak
A: 

SimpleXMLElement::asXML does it if you are on SimpleXML.

Tomalak
unfortunately this gives the *outer* html as well as the <?xml processor instructions.
nickf