phphtmldomsimple-html-dom

Stuck selecting classes or id's using PHP Simple HTML DOM Parser


I'm trying to select either a class or an id using PHP Simple HTML DOM Parser with absolutely no luck. My example is very simple and seems to comply to the examples given in the manual(http://simplehtmldom.sourceforge.net/manual.htm) but it just wont work, it's driving me up the wall. Other example scripts given with simple dom work fine.

<?php
include_once('simple_html_dom.php');  
$html =  str_get_html('<html><body><div id="foo">Hello</div><div class="bar">Goodbye</div></body></html>');  
$ret = $html->find('.bar')->plaintext;  
echo $ret;  
print_r($ret);  

Can anyone see where I'm going wrong?


Solution

  • $html->find('.bar'); will return a collection of matching elements, so you need to pass an index as the second parameter:

    $ret = $html->find('.bar', 0)->plaintext;
    

    or loop through the matches:

    foreach($html->find('.bar') as $element) {
        echo $element->plaintext . '<br />';
    }