dongli7870 2015-01-13 17:47
浏览 54
已采纳

递归解析功能

I made a function that parses a certain page of a website(a forum thread). It should select users and their posts and then go on to the next page and do the same. While it does that, its return value is always null. I think I made a mistake with the recursion, but can't really figure it out.

Here is the function, I made it return only the userlist, for now.

function getWinners( $thread,$userlist,$postlist ) {
    //libxml_use_internal_errors(true);
    $html = file_get_html( $thread );


    //get users
    $users=$html->find( 'li[class="postbitlegacy postbitim postcontainer old"] div[class=username_container] strong span' );
    foreach ( $users as $user )
        //echo $user . '<br>';
        array_push( $userlist, $user );
    //get posts
    $posts=$html->find( 'li[class="postbitlegacy postbitim postcontainer old"] div[class=postbody] div[class=content]' );
    foreach ( $posts as $post )
        // echo $post . '<br>';
        array_push( $postlist, $post );
    //check if there is a next page
    if ( $next=$html->find( 'span[class=prev_next] a[rel="next"]', 0 ) ) {
        $testa='http://forums.heroesofnewerth.com/'.$next->href;
        // echo $testa. '<br>';
        $html->clear();
        unset( $html );

        //recursive calls until the last page of the forum thread
        getWinners( $testa,$userlist,$postlist );

     //no more thread, return users
    }else return $userlist;
}

And the call

$thread='http://forums.heroesofnewerth.com/showthread.php?553261';

    $userlist=array();
    $postlist=array();

 $stuff=getWinners( $thread,$userlist,$postlist);
 echo $stuff[0];

Here, stuff is empty.

  • 写回答

1条回答 默认 最新

  • doushi3202 2015-01-13 17:57
    关注

    At the very least you would need to use the value returned from the recursive function:

    getWinners( $testa,$userlist,$postlist );
    

    should be:

    return getWinners( $testa,$userlist,$postlist );
    // or, more likely:
    return array_merge($users, getWinners($testa,$userlist,$postlist));
    

    Apart from that I'm not sure if you are returning the right information, probably (you'd need to check...) you need something like:

        //cursive calls until the last page of the forum thread
        return array_merge($userlist, getWinners($testa,$userlist,$postlist));
    }
    else {
        //no more thread, return users
        return $userlist;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 帮我写一段可以读取LD2450数据并计算距离的Arduino代码
  • ¥15 C#调用python代码(python带有库)
  • ¥15 矩阵加法的规则是两个矩阵中对应位置的数的绝对值进行加和
  • ¥15 活动选择题。最多可以参加几个项目?
  • ¥15 飞机曲面部件如机翼,壁板等具体的孔位模型
  • ¥15 vs2019中数据导出问题
  • ¥20 云服务Linux系统TCP-MSS值修改?
  • ¥20 关于#单片机#的问题:项目:使用模拟iic与ov2640通讯环境:F407问题:读取的ID号总是0xff,自己调了调发现在读从机数据时,SDA线上并未有信号变化(语言-c语言)
  • ¥20 怎么在stm32门禁成品上增加查询记录功能
  • ¥15 Source insight编写代码后使用CCS5.2版本import之后,代码跳到注释行里面