Search code examples
phphtmlsimple-html-dom

getting element content with simpe-html-dom


I'm using simpile_html_dom for getting html pages elements. I have some div elements like this. All i want is to get "Fine Thanks" sentence in each div (that is not inside any sub-element). How can i do it?

<div class="right">
<h2>
<a href="">Hello</a>
</h2>
<br/>
<span>How Are You?</span>
<span>How Are You?</span>
<span>How Are You?</span>
Fine Thanks
</div>

Solution

  • There is no built in method to read text property in simple_html_dom.php
    But this should work;

    include 'parser.php';
    
    $html = str_get_html('<div class="right">
    <h2>
    <a href="">Hello</a>
    </h2>
    <br/>
    <span>How Are You?</span>
    <span>How Are You?</span>
    <span>How Are You?</span>
    Fine Thanks
    </div>');
    
    function readTextNode($element){
        $local = $element;
        $childs = count($element->childNodes());
        for($i = 0; $i < $childs; $i++)
            $local->childNodes($i)->outertext = '';
        return $local->innertext;
    }
    
    echo readTextNode($html->find('div.right',0));