I have document from which I want to extract specific div with it's untouched content. I do:
$dom = new DOMDocument();
$dom->loadHTML($string);//that's HTML of my document, string
and xpath query:
$xpath = new DOMXPath($dom);
$xpath_resultset = $xpath->query("//div[@class='text']");
/*I'm after div class="text"*/
now I do item(0)
method on what I get with $xpath_resultset
$my_content = $xpath_resultset->item(0);
what I get is object (not string) $my_content which I can echo or settype() to string, but as result I get is with fully stripped markup?
What to do to get all from div class='text' here?
DOM and XPath are different concepts. DOM (Document Object Model) is a representation of a document or document fragment consisting of XML nodes arranged as a tree. XPath is a syntax for expressing a navigation through a DOM to locate one or more nodes.
The DOMXPath::query() function is an inbuilt function in PHP which is used to evaluate the given XPath expression. Syntax: DOMNodeList DOMXPath::query( string $expression, DOMNode $contextnode, bool $registerNodeNS )
Just pass the node to the DOMDocument::saveHTML
method:
$htmlString = $dom->saveHTML($xpath_resultset->item(0));
This will give you a string representation of that particular DOMNode and all its children.
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