【问题标题】:Finding and Printing all Links within a DIV查找并打印 DIV 中的所有链接
【发布时间】:2011-02-26 03:50:41
【问题描述】:

我正在尝试查找 div 中的所有链接,然后打印这些链接。

我正在使用 Simple HTML Dom 来解析 HTML 文件。这是我到目前为止的内容,请阅读内联 cmets 并让我知道我哪里出错了。

include('simple_html_dom.php');  

$html = file_get_html('tester.html');

$articles = array();

//find the div the div with the id abcde
foreach($html->find('#abcde') as $article) {

    //find all a tags that have a href in the div abcde
    foreach($article->find('a[href]') as $link){

        //if the href contains singer then echo this link
        if(strstr($link, 'singer')){

            echo $link;

        }

    }

}

目前发生的情况是上述内容需要很长时间才能加载(从未完成)。我打印了它在每个循环中所做的事情,因为等待时间太长,我发现它正在经历我不需要的事情!这表明我的代码是错误的。

HTML 基本上是这样的:

<div id="abcde">
<!-- lots of html elements -->
<!-- lots of a tags -->
<a href="singer/tom" />
<img src="image..jpg" />
</a>
</div>

感谢大家的帮助

【问题讨论】:

    标签: php dom parsing


    【解决方案1】:

    为什么不使用内置的 DOM 扩展呢?

    <?php
    
    $cont = file_get_contents("http://stackoverflow.com/") or die("1");
    
    $doc = new DOMDocument();
    @$doc->loadHTML($cont) or die("2");
    
    $nodes = $doc->getElementsByTagName("a");
    
    for ($i = 0; $i < $nodes->length; $i++) {
        $el = $nodes->item($i);
        if ($el->hasAttribute("href"))
            echo "- {$el->getAttribute("href")}\n";
    }
    

    给予

    ...(之前有很多链接)... - http://careers.stackoverflow.com - http://serverfault.com - http://superuser.com - http://meta.stackoverflow.com - http://www.howtogeek.com - http://doctype.com - http://creativecommons.org/licenses/by-sa/2.5/ - http://www.peakinternet.com/business/hosting/colocation-dedicated# - http://creativecommons.org/licenses/by-sa/2.5/ - http://blog.stackoverflow.com/2009/06/attribution-required/

    【讨论】:

      【解决方案2】:

      使用该 API 按 ID 选择 div(或其他)的正确方法是:

      $html->find('div[id=abcde]');
      

      此外,由于 ID 应该是唯一的,因此以下内容就足够了:

      //find all a tags that have a href in the div abcde
      $article = $html->find('div[id=abcde]', 0);
      
      foreach($article->find('a[href]') as $link){
      
          //if the href contains singer then echo this link
          if(strstr($link, 'singer')){
              echo $link;
          }
      }
      

      【讨论】:

      • 太棒了,它立即生效!对于选择器,我必须处于 JQuery 模式。
      猜你喜欢
      • 2011-09-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-21
      • 2019-07-15
      • 2011-02-17
      • 1970-01-01
      相关资源
      最近更新 更多