如何在<a> tag with Simple HTML DOM Parser?

时间:2017-08-20 09:29:38

标签: php html dom domparser

<ul id="PrList" class="v2">
    <li class="tools">

    </li>
    <li class="firstRow">
        <div class="i">
            <a href="www.google.com" title="Google" class="nC">
                <img src="something">
            </a>
        </div>
    </li>
</ul>

How to get just href attribute in <div class="i">?

I tried this-

$html = file_get_html($link);
$urls = [];
foreach($html->find('.i') as $element) {
   $url = $element->find('.nC')->href;
   if (!in_array($url, $urls)) {
       echo $url . "<br/>";
       $urls[] = $url;
   }
}

but I received an error:-

Notice: Trying to get property of non-object

and I tried:-

$html = file_get_html($link);
$html = $html->find('div.i');
$html -> find('a',0)->href; 
$echo $html;

but I received an error again:-

Fatal error: Call to a member function find() on array

2 个答案:

答案 0 :(得分:2)

你需要像下面这样做: -

$html = file_get_html($link);
$urls = [];
foreach($html->find('.i a') as $element) {
   $url = $element->href;
   if (!in_array($url, $urls)) {
       echo $url . "<br/>";
       $urls[] = $url;
   }
}
echo "<pre/>";print_r($urls);

答案 1 :(得分:0)

试试这个循环。

foreach($html->find('div[class=i] a') as $a){
  var_dump($a->attr);
}