我想创建一个PHP函数,通过一个网站的主页,找到主页中的所有链接,通过它找到的链接,并继续进行,直到所有的链接在说的网站是最终的。我真的需要建立这样的东西,这样我就可以蜘蛛我的网站网络,并提供“一站式”的搜索。
这是我到目前为止得到的-
function spider($urltospider, $current_array = array(), $ignore_array = array('')) {
    if(empty($current_array)) {
        // Make the request to the original URL
        $session = curl_init($urltospider);
        curl_setopt($session, CURLOPT_RETURNTRANSFER, true);
        $html = curl_exec($session);
        curl_close($session);
        if($html != '') {
            $dom = new DOMDocument();
            @$dom->loadHTML($html);
            $xpath = new DOMXPath($dom);
            $hrefs = $xpath->evaluate("/html/body//a");
            for($i = 0; $i < $hrefs->length; $i++) {
                $href = $hrefs->item($i);
                $url = $href->getAttribute('href');
                if(!in_array($url, $ignore_array) && !in_array($url, $current_array)) {
                    // Add this URL to the current spider array
                    $current_array[] = $url;
                }
            }               
        } else {
            die('Failed connection to the URL');
        }
    } else {
        // There are already URLs in the current array
        foreach($current_array as $url) {
            // Connect to this URL
            // Find all the links in this URL
            // Go through each URL and get more links
        }
    }
}唯一的问题是,我似乎不知道该怎么做。有人能帮我吗?基本上,此函数将重复执行,直到找到所有内容为止。
发布于 2010-07-18 14:12:36
您要查找的单词是recursion。在foreach循环中,您只需再次调用spider,它将进入每个URL的函数并递归地执行爬行。
但是有一个相当重要的问题-你没有基本情况,除非你最终到达的页面没有链接到其他页面(死胡同)。此函数将永远运行,并且不会终止。你需要用几种方式来绑定它。
https://stackoverflow.com/questions/3274504
复制相似问题