Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get innerhtml of an element from PHP

Tags:

php

I have two files: mainpage.html and recordinput.php

I need get a div's innerhtml from the mainpage.html in my php file.

I have copied the code here:

in my php file, I have

$dochtml = new DOMDocument();
//libxml_use_internal_errors(true);
$dochtml->loadHTMLFile("mainpage.html");

$div = $dochtml->getElementById('div2');
$div2html = get_inner_html($div);
echo "store information as: ".$div2html;


function get_inner_html(DOMNode $elem ) 
{

    $innerHTML = " ";
$children = $elem->childNodes;

foreach ($children as $child)
{
    $innerHTML .= $elem->ownerDocument->saveHTML( $child );
}
echo "function return: ".$innerHTML."<br />";
return $innerHTML;
 }

The return is just empty. Any body helps me? I have spent two days on this. I feel like the problem is in here:

$dochtml->loadHTMLFile("mainpage.html");

Thanks

like image 306
yunyun Avatar asked Mar 16 '15 17:03

yunyun


2 Answers

PHP DOMDocument has already provided the function to retrieve content between your selectors. Here is how you do it

$div = $dochtml->getElementById('div2')->nodeValue;

So you don't need to make your own function.

like image 57
Raheel Avatar answered Sep 25 '22 20:09

Raheel


If you're looking to get the div contents including all nested tags then you can do it like this:

echo $div->ownerDocument->saveHTML($div);

Example: http://3v4l.org/GCbJk

Note that this includes the div2 tag itself, which you could easily then strip off.

like image 24
JoeCoder Avatar answered Sep 24 '22 20:09

JoeCoder