0

我正在尝试编写一个 php 解析器来从 ratemyprofessor.com 收集教授评论。每个教授都有一个页面,其中包含所有评论,我想解析每个教授的网站并将评论提取到 txt 文件中。这是我到目前为止所拥有的,但是当我运行它时它没有正确执行,因为输出 txt 文件仍然是空的。可能是什么问题?

<?php     
set_time_limit(0);

$domain = "http://www.ratemyprofessors.com";
$content = "div id=commentsection";
$content_tag = "comment";
$output_file = "reviews.txt";
$max_urls_to_check = 400;
$rounds = 0;
$reviews_stack = array();
$max_size_domain_stack = 10000;
$checked_domains = array();


while ($domain != "" && $rounds < $max_urls_to_check) {
    $doc = new DOMDocument();
    @$doc->loadHTMLFile($domain);
    $found = false;


    foreach($doc->getElementsByTagName($content_tag) as $tag) {
        if (strpos($tag->nodeValue, $content)) {
            $found = true;
            break;
        }
    }

    $checked_domains[$domain] = $found;
    foreach($doc->getElementsByTagName('a') as $link) {
        $href = $link->getAttribute('href');
        if (strpos($href, 'http://') !== false && strpos($href, $domain) === false) {
            $href_array = explode("/", $href);

            if (count($domain_stack) < $max_size_domain_stack &&
                $checked_domains["http://".$href_array[2]] === null) {
                array_push($domain_stack, "http://".$href_array[2]);
            }
        };
    }


    $domain_stack = array_unique($domain_stack);
    $domain = $domain_stack[0];
    unset($domain_stack[0]);
    $domain_stack = array_values($domain_stack);
    $rounds++;
}

$found_domains = "";
foreach ($checked_domains as $key => $value) {
    if ($value) {
        $found_domains .= $key."\n";
    }
}


file_put_contents($output_file, $found_domains); 
?>
4

1 回答 1

0

这是我到目前为止所拥有的,但是当我运行它时它没有正确执行,因为输出 txt 文件仍然是空的。可能是什么问题?

由于缺少数组变量初始化,它给出了空输出。

  1. 主要部分。添加变量的初始化:

    $domain_stack = array(); // before while ($domain != ...... )
    
  2. 额外的。修复其他警告和通知:

    // change this
    $checked_domains["http://".$href_array[2]] === null
    
    // into
    
    !isset($checked_domains["http://".$href_array[2]])
    
    // another line
    // check if key exists
    if (isset($domain_stack[0]))  {
      $domain = $domain_stack[0];
      unset($domain_stack[0]);
    }
    
于 2012-12-17T10:55:24.043 回答