Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP retrieve inner HTML as string from URL using DOMDocument [duplicate]

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

like image 309
Dan Kanze Avatar asked Aug 29 '26 01:08

Dan Kanze


2 Answers

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();
like image 176
anubhava Avatar answered Aug 30 '26 15:08

anubhava


<?php

$f = curl_get_file_contents('http://example.com/')

$dom = new DOMDocument();
@$dom->loadHTML($f);
$data = $dom->getElementById("profile_section_container");
$html = $dom->saveHTML($data);
echo $html;

?>

It would help if you provided the example html.

like image 27
Motes Avatar answered Aug 30 '26 15:08

Motes