2010-06-01 53 views
1

我正在尝试查找div中的所有链接,然后打印这些链接。查找并打印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> 

感谢所有使用该API的任何帮助

回答

2

(不管或)正确的方式来选择一个div的ID是:

$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; 
    } 
} 
+0

真棒,它的工作马上!我必须为选择器使用JQuery模式。 – Abs 2010-06-01 00:34:43

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/ 
相关问题