2016-02-12 31 views
0

我想抓住一个HTML内的img标签。该HTML看起来有点像这样:PHP的DOMDocument:getElementsbyTagName('IMG')不工作

<img style='width:198px;height:279px;'   class='featureImg'    src='image-loader.gif'   data-src='http://somesites.com/med/1455.jpg'   alt="Picture"> 
 
    

现在我要抢IMG SRC http://somesites.com/med/1455.jpg

$dom = new DOMDocument(); 
libxml_use_internal_errors(true); 
$dom->loadHTML($html); 
$divs = $dom->getElementsByTagName('img'); 
foreach ($divs as $div){ 
    if(preg_match_all('/\bfeatureImg\b/', $div->getAttribute('class'))) { 
     $links = $div->getElementsByTagName('img'); 
     foreach($links as $link){ 
       $li = $link->getAttribute('data-src'); 

       echo ($li.'<br>'); 

}}} 

并没有工作...任何人的帮助?

+0

不应该是'$ link-> getAttribute('src');'? – andre3wap

回答

0

这已经给你一个图片:

$divs = $dom->getElementsByTagName('img'); 

因此,如果preg_match_all比赛中,你可以得到 '数据-SRC' 属性:

$html = <<<SOURCE 
<img style='width:198px;height:279px;'   class='featureImg'    src='image-loader.gif'   data-src='http://somesites.com/med/1455.jpg'   alt="Picture"> 
SOURCE; 
$dom = new DOMDocument(); 
libxml_use_internal_errors(true); 
$dom->loadHTML($html); 

$divs = $dom->getElementsByTagName('img'); 
foreach ($divs as $div) { 
    if (preg_match_all('/\bfeatureImg\b/', $div->getAttribute('class'))) { 
     echo $div->getAttribute('data-src'); 
    } 
} 

会导致:

http://somesites.com/med/1455.jpg