Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the html inside a $node rather than just the $nodeValue [duplicate]

Description of the current situation:

I have a folder full of pages (pages-folder), each page inside that folder has (among other things) a div with id="short-info".
I have a code that pulls all the <div id="short-info">...</div> from that folder and displays the text inside it by using textContent (which is for this purpose the same as nodeValue)

The code that loads the divs:

<?php
$filename = glob("pages-folder/*.php");
sort($filename);
foreach ($filename as $filenamein) {
    $doc = new DOMDocument();
    $doc->loadHTMLFile($filenamein);
    $xpath = new DOMXpath($doc);
    $elements = $xpath->query("*//div[@id='short-info']");

        foreach ($elements as $element) {
            $nodes = $element->childNodes;
            foreach ($nodes as $node) {
                echo $node->textContent;
            }
        }
}
?>

Now the problem is that if the page I am loading has a child, like an image: <div id="short-info"> <img src="picture.jpg"> Hello world </div>, the output will only be Hello world rather than the image and then Hello world.

Question:

How do I make the code display the full html inside the div id="short-info" including for instance that image rather than just the text?

like image 918
EEC Avatar asked Jul 18 '11 21:07

EEC


People also ask

What is nodeValue in html?

Definition and UsageThe nodeValue property sets or returns the value of a node. If the node is an element node, the nodeValue property will return null. Note: If you want to return the text of an element, remember that text is always inside a Text node, and you will have to return the Text node's node value (element.

What does nodeValue do in javascript?

The nodeValue property of the Node interface returns or sets the value of the current node.

Is nodeValue same as value?

The value of an input element is available from its value property. nodeValue is a property of all DOM nodes, and not relevant to input elements.


2 Answers

You have to make an undocumented call on the node.

$node->c14n() Will give you the HTML contained in $node.

Crazy right? I lost some hair over that one.

http://php.net/manual/en/class.domnode.php#88441

Update

This will modify the html to conform to strict HTML. It is better to use

$html = $Node->ownerDocument->saveHTML( $Node );

Instead.

like image 191
Byron Whitlock Avatar answered Oct 08 '22 03:10

Byron Whitlock


You'd want what amounts to 'innerHTML', which PHP's dom doesn't directly support. One workaround for it is here in the PHP docs.

Another option is to take the $node you've found, insert it as the top-level element of a new DOM document, and then call saveHTML() on that new document.

like image 27
Marc B Avatar answered Oct 08 '22 02:10

Marc B