查找和打印DIV中的所有链接 [英] Finding and Printing all Links within a DIV

查看:70
本文介绍了查找和打印DIV中的所有链接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在div中查找所有链接,然后打印这些链接.

I am trying to find all links in a div and then printing those links.

我正在使用简单HTML Dom解析HTML文件.这是我到目前为止的内容,请阅读内联注释,让我知道我要去哪里了.

I am using the Simple HTML Dom to parse the HTML file. Here is what I have so far, please read the inline comments and let me know where I am going wrong.

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;

        }

    }

}

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

What currently happens is that the above takes a long time to load (never got it to finish). I printed what it was doing in each loop since it was too long to wait and I find that its going through things I don't need it to! This suggests my code is wrong.

HTML基本上是这样的:

The HTML is basically something like this:

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

感谢所有帮助

推荐答案

使用该API通过ID选择div(或其他任何内容)的正确方法是:

The correct way to select a div (or whatever) by ID using that API is:

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

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

Also, since IDs are supposed to be unique, the following should suffice:

//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;
    }
}

这篇关于查找和打印DIV中的所有链接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆