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

报告相同问题?

悬赏问题

  • ¥15 springboot 3.0 实现Security 6.x版本集成
  • ¥15 PHP-8.1 镜像无法用dockerfile里的CMD命令启动 只能进入容器启动,如何解决?(操作系统-ubuntu)
  • ¥15 请帮我解决一下下面六个代码
  • ¥15 关于资源监视工具的e-care有知道的嘛
  • ¥35 MIMO天线稀疏阵列排布问题
  • ¥60 用visual studio编写程序,利用间接平差求解水准网
  • ¥15 Llama如何调用shell或者Python
  • ¥20 谁能帮我挨个解读这个php语言编的代码什么意思?
  • ¥15 win10权限管理,限制普通用户使用删除功能
  • ¥15 minnio内存占用过大,内存没被回收(Windows环境)