PHP DOM解析多个页面使用while循环多次加载单页语句

时间:2017-04-09 10:08:45

标签: php mysql web-crawler

我试图使用PHP dom解析器从论坛网站解析与帖子相关的语句。它在我们插入页面的单个url时有效,但是当我们尝试应用while循环逻辑时,它只打印多次一页...

我的代码为::

<?php
    set_time_limit(3600);
      $i = 1;
      $e = 839304-$i;
     while(true){
    require_once('dom/simple_html_dom.php'); 
$html =file_get_html('http://www.usmleforum.com/files/forum/2017/1/'.$e.'.php');
    foreach ($html->find("tr") as $row) {
    $element = $row->find('td.Text2',0);
    if ($element == null) { continue; }
    $textNode = array_filter($element->nodes, function ($n) {
    return $n->nodetype == 3;        //Text node type, like in jQuery     
});
    if (!empty($textNode)) {
    $text = current($textNode);
    echo $text."<br>"; 
}
}
    $i++;
}
?>

结果表明,它只打印来自第839303页的语句,但它打印多次并仍然加载..所以很明显,这段代码以某种方式跳过$ i ++行并再次运行......

感谢任何帮助...

1 个答案:

答案 0 :(得分:0)

在{while}循环内插入$e将解决问题。但它是一个infine循环。所以尝试为while循环提供退出条件,如:while($i < 100)或其他。

 <?php
    set_time_limit(3600);
      $i = 0;

     while($i < 10){
     $e = 839303 + $i;
    require_once('dom/simple_html_dom.php'); 
$html =file_get_html('http://www.usmleforum.com/files/forum/2017/1/'.$e.'.php');
    foreach ($html->find("tr") as $row) {
    $element = $row->find('td.Text2',0);
    if ($element == null) { continue; }
    $textNode = array_filter($element->nodes, function ($n) {
    return $n->nodetype == 3;        //Text node type, like in jQuery     
});
    if (!empty($textNode)) {
    $text = current($textNode);
    echo $text."<br>"; 
}
}
    $i++;
}
?>
相关问题