递归PHP函数return允许的内存大小用尽

时间:2018-11-10 03:06:30

标签: php dom simple-html-dom

我正在研究一个小型DOM项目,以获取动态链接和静态链接。但是我的函数要花很多时间才能执行,并且返回错误,如您所见

allowed memory size of bytes exhausted

这是我的PHP代码:

public $domain_name = 'www.example.com'; 
public function dynamic_url2($url = "http://www.example.com"){
    $pages = array();
    $html = file_get_html($url);
    foreach($html->find('a') as $page){
        if(valid_url($page->href)){
            $parse_page = parse_url($page->href);
            if($parse_page['host'] == $this->domain_name){
                if(!in_array($page->href, $pages)){
                    $pages[] = $page->href;
                    if(array_key_exists('query', $parse_page))
                        echo 'contain dynamic parameters : '. $page->href.'<br>';
                    else
                        echo 'not dynamic : '. $page->href.'<br>';
                }
                return $this->dynamic_url2($page->href);
            }
        }
    }
}

我的功能正确吗?我如何优化它?

谢谢

1 个答案:

答案 0 :(得分:0)

除了我在测试时进行的一些细微调整之外,您只需要使$pages可修改(通过函数声明中的&$pages)并在每次递归调用时传递$pages数组

public $domain_name = 'https://www.example.html'; 
public function dynamic_url2($url, &$pages = []){
    //echo "<div>Crawling $url</div>";
    $dom = new DOMDocument;
    libxml_use_internal_errors(true);  // for malformed html warning suppression
    $dom->loadHTML(file_get_contents($url));  // this doesn't account for relative urls
    $xpath = new DOMXPath($dom);
    foreach ($xpath->query("//a") as $a) {
        $href = $a->getAttribute('href');
        //echo "<div>Found $href @ $url</div>";
        if (valid_url($href)) {
            $parsed = parse_url($href);
            if ($parsed['host'] == $this->domain_name && !in_array($href, $pages)) {
                $pages[] = $href;
                //echo "<div>$href is " , (array_key_exists('query', $parsed) ? '' : 'not ') , 'dynamic</div>';
                $this->dynamic_url2($href, $pages);
            } else {
                //echo "<div>Ignored url: $href</div>";
            }
        } else {
            //echo "<div>Invalid url: $href</div>";
        }
    }
    return $pages;    
}
var_export($this->dynamic_url2($this->domain_name));