Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extract innerHTML using the PHP Dom [duplicate]

I'm currently using nodeValue to give me HTML output, however it is stripping the HTML code and just giving me plain text. Does anyone know how I can modify my code to give me the inner HTML of an element by using it's ID?

function getContent($url, $id){

// This first section gets the HTML stuff using a URL
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
$html = curl_exec($ch);
curl_close($ch);

// This second section analyses the HTML and outputs it
$newDom = new domDocument;
$newDom->loadHTML($html);
$newDom->preserveWhiteSpace = false;
$newDom->validateOnParse = true;

$sections = $newDom->getElementById($id)->nodeValue;
echo $sections;


}
like image 751
user1259294 Avatar asked Feb 22 '26 22:02

user1259294


1 Answers

This works for me:

$sections = $newDom->saveXML($newDom->getElementById($id));

http://www.php.net/manual/en/domdocument.savexml.php

If you have PHP 5.3.6, this might also be an option:

$sections = $newDom->saveHTML($newDom->getElementById($id));

http://www.php.net/manual/en/domdocument.savehtml.php

like image 181
Martin Avatar answered Feb 24 '26 14:02

Martin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!