Jump to content

count child nodes in phpsimpledom

Recommended Posts

Hi guys,

I'm using PHP Simple DOM, thanks to the good folk her I'm making progress. The html i'm parsing has a bunch of links in a li ul structure. I've managed to get the top layer of links extracted and I would like to have a count of the number of child nodes in the layer below the main links. Here is my code:

$html = file_get_html('test/php/book.html');

    $lis = $html->find('.chunklist', 0)->children() ;

    for ( $i = 0 ; $i < count($lis) ; $i++ ) {

        $parent_term = $lis[$i]->first_child()->innertext . ', ' ;
        $parent_node = $lis[$i]->children[0]->attr['href'] . '<br>' ; 
        //echo count($parent_node->children()) ; this gives error Warning: count(): Parameter must be an array or an object that implements Countable
        echo $parent_term . $parent_node ;

        $parent_node = $const . $parent_node ; 
        echo $parent_node ;
        $html2 = file_get_html($parent_node) ;
        $lis2 = $html2->find('.chunklist', 0)->children() ; 

I don't see anything in the manual regarding counting nodes, any idea how to go about this?

Share this post

Link to post
Share on other sites

Are you looking to count what you get from the following line?

$lis2 = $html2->find('.chunklist', 0)->children() ;

If so, have you tried PHP's count() function?


Note that I haven't used PHP Simple DOM. So I'm just guessing here. 😁

Share this post

Link to post
Share on other sites

Good guess!

Yeah I tried that, but some of the $lis2 don't have children, and I'm not sure how to deal with null results,

$lis2 = $html2->find('.chunklist', 0)->children() ;

results in:

Fatal error: Uncaught Error: Call to a member function children() on null

I've tried:

        for ( $j = 0 ; $j < count($lis2) ; $j++ ) {
            if ($lis2 > 0) {  // and tried $lis2 <> 0
                $parent_term = $lis2[$j]->first_child()->innertext . ', ' ;
                $parent_node = $lis2[$j]->children[0]->attr['href'] . '<br>' ; 
               // echo count( $parent_node ) ;
            } else {

                echo "no data found" ;

kinda stuck as to what to try next?

Share this post

Link to post
Share on other sites

According to the documentation, find() returns null if the requested object isn't found. So check for null before you attempt the children() call - right now you're checking if $lis2 is greater than 0.

Share this post

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now


Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.