PHP retrieve inner HTML as string from URL using DOMDocument

cross-domain, dom, html, php

Solution

This is the code you will need to avoid any malformed HTML errors:

$dom = new DOMDocument();
libxml_use_internal_errors(true);
$dom->loadHTMLFile('http://example.com/');
$data = $dom->getElementById("banner");
echo $data->nodeValue."\n"

To dump whole HTML source you can call:

echo $dom->saveHTML();

Problem

I've been picking bits and pieces of code, you can see roughly what I'm trying to do, obviously this doesn't work and is utterly wrong: ``` <?php $dom= new DOMDocument(); $dom->loadHTMLFile('http://example.com/'); $data = $dom->getElementById("profile_section_container"); $html = $data->saveHTML(); echo $html; ?> ``` Using a CURL call, I am able to retrieve the document URL source: ``` function curl_get_file_contents($URL) { $c = curl_init(); curl_setopt($c, CURLOPT_RETURNTRANSFER, 1); curl_setopt($c, CURLOPT_URL, $URL); $contents = curl_exec($c); curl_close($c); if ($contents) return $contents; else return FALSE; } $f = curl_get_file_contents('http://example.com/'); echo $f; ``` So how can I use this now to instantiate a DOMDocument object in PHP and extract a node using getElementById

Original source

Related problems