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.
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?
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.
The nodeValue property of the Node interface returns or sets the value of the current node.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With