Поиск и печать всех ссылок в 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> 

Спасибо всем за любую помощь

Solutions Collecting From Web of "Поиск и печать всех ссылок в DIV"

Правильный способ выбора идентификатора div (или любого другого) с помощью этого API:

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

Кроме того, поскольку идентификаторы должны быть уникальными, должно быть достаточно:

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

Почему бы вам не использовать встроенное расширение 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/