Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get full HTML from DOMXPath::query() method?

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?

like image 801
Miloš Đakonović Avatar asked Jun 09 '13 17:06

Miloš Đakonović


People also ask

What is DOMXPath in HTML?

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.

What is DOMXPath in PHP?

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 )


1 Answers

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.

like image 174
Tim Cooper Avatar answered Oct 10 '22 03:10

Tim Cooper