2016-02-12 44 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