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;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 关于php录入完成后,批量更新数据库
  • ¥15 请教往复密封润滑问题
  • ¥15 cocos creator发布ios包
  • ¥15 comsol压电材料数据
  • ¥35 用python实现除法算法中goldschmidt算法
  • ¥15 汇编代码转换成C代码
  • ¥15 除法算法中的归一化具体是怎么变的?
  • ¥20 集成电路的逻辑电路和晶体管简化图
  • ¥15 下载windows builder后的问题
  • ¥15 端口连接数为什么会有限制