20

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
  • 23,183
  • 12
  • 55
  • 64
Miloš Đakonović
  • 3,751
  • 5
  • 35
  • 55

1 Answers1

55

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.

  • 7
    That method requires PHP 5.3.6, an alternative is to use DOMDocument::saveXML which only requires PHP 5. – Kyle Jun 09 '13 at 18:41