Jump to content

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');

if(!empty($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?

Link to comment
https://forums.phpfreaks.com/topic/308410-count-child-nodes-in-phpsimpledom/
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?

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

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.