19

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?

Fabio
  • 22,442
  • 12
  • 51
  • 63
Miloš Đakonović
  • 3,541
  • 5
  • 32
  • 49

1 Answers1

52

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.

Tim Cooper
  • 151,519
  • 37
  • 317
  • 271