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

Miloš Đakonović picture Miloš Đakonović · Jun 9, 2013 · Viewed 21.8k times · Source

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?

Answer

Tim Cooper picture Tim Cooper · Jun 9, 2013

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.