XPath in PHP Removes HTML Tags

I am using XPath in PHP to extract parts of an HTML document. Suppose my HTML document looked like this:

<html>
    <head>
    </head>
    <body>
        <div id="first">
            <a href="some_link_address.com">Hello</a>
            <p>Some text here</p>
        </div>
        <div id="second">
            <p>Some other text here</p>
            <img src="src/to/image.jpg" />
        </div>
    </body>
</html>

And my PHP, including the XPath call:

$result_dom = new DOMDocument('1.0', 'utf-8');
$node_to_keep = $xpath->query("//div[@id='first']");

foreach ($nodes_to_keep as $node) {

    $element = $result_dom->createElement('div', $node->nodeValue;);
    $result_dom ->appendChild($element);
}

I expected that as a result, dom would contain the following

<div>
    <a href="some_link_address.com">Hello</a>
    <p>Some text here</p>
</div>

However, this is the result of dom

<div>
    Hello
    Some text here
</div>

So my question is: how to install the resulting dom containing html tags. I do not want them to be deleted

Thanks.

+4
source share
1 answer

The "nodeValue" of an element is the text content of this element. Text nodes in a document do not include <a ...>, etc., Only text inside and between these elements. So, that’s all you get in the new element.

node node :

$importedNode = $result_dom->importNode($node, true);
$result_dom->appendChild($importedNode);
+2

All Articles