查找并打印DIV中的所有链接

时间:2010-06-01 00:24:59

标签: php dom parsing

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

我正在使用Simple HTML Dom来解析HTML文件。以下是我到目前为止的内容,请阅读内联评论,并告诉我出错的地方。

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>

感谢大家的帮助

2 个答案:

答案 0 :(得分:3)

使用该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;
    }
}

答案 1 :(得分:0)

为什么不使用内置的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";
}

给出

... (lots of links before) ...
- 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/
相关问题