How to get xml content in node as string?

Using the PHP DOM functions, how do you convert the contents of the DOM Node to a string?

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

Given foohow the current context is a node, how do you get 'Blah blah <bar baz="1">bah</bar> blah blah'as a string? Using $node->textContentor $node->nodeValuejust returns text nodes, not <bar baz="1">.

Basically, the equivalent of a Javascript property innerHTML...

+3
source share
1 answer

You can create a new DOMDocument from <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)); 
}
+5
source

Source: https://habr.com/ru/post/1710543/


All Articles