1

All I want to do is save the first div with attribute role="main" as a string from an external URL using PHP.

So far I have this:

$doc = new DOMDocument();
@$doc->loadHTMLFile("http://example.com/");

$xpath = new DOMXPath($doc);
$elements = $xpath->query('//div[@role="main"]');
$str = "";
if ($elements->length > 0) {
    $str = $elements->item(0)->textContent;
}
echo htmlentities($str);

But unfortunately the $str does not seem to be displaying the HTML tags. Just the text.

halfer
  • 19,824
  • 17
  • 99
  • 186
Yahya Uddin
  • 26,997
  • 35
  • 140
  • 231

1 Answers1

1

You can get the HTML via the saveHTML() method.

$str = $doc->saveHTML($elements->item(0));

Yahya Uddin
  • 26,997
  • 35
  • 140
  • 231
Rob W
  • 9,134
  • 1
  • 30
  • 50