2013-07-16 31 views
0

我使用這個腳本從一個普通的外部網頁得到所有圖片:如何在所有情況下從網頁獲取所有圖像?

$url = ANY URL HERE; 
$html = @file_get_contents($url,false,$context); 
$dom = new domDocument; 
@$dom->loadHTML($html); 
$dom->preserveWhiteSpace = false; 
$images = $dom->getElementsByTagName('img'); 

foreach ($images as $image) { 
echo $image->getAttribute('src'); 
} 

但在某些情況下,像這樣(其中圖像是「REL:image_src」)

<img src="http://example.com/example.png" rel:image_src="http://example.com/dir/me.jpg" /> 

它不起作用。

我該怎麼辦?

+1

'$ image-> getAttribute('rel:image_src')'? – Leri

+0

問題是,有時候是rel:image_src,有時候是rel:ax_image_src,有時候是si rel:img_src等等,所以有不一樣的屬性。所以用這種方式它不會工作:( – xRobot

回答

0

檢查如果你希望rel:image_src採取precidence,檢查屬性的存在,並有選擇地使用它的節點有一個屬性rel:image_src

foreach ($images as $image) { 
    if($image->hasAttribute('rel:image_src')) { 
    echo $image->getAttribute('rel:image_src'); 
    } else { 
    echo $image->getAttribute('src'); 
    } 
} 
+0

問題是,有時是rel:image_src,有時是rel:ax_image_src,有時si rel:img_src等等。所以它們不是相同的屬性,所以這樣就不會工作:( – xRobot

+0

好吧,那麼你怎麼知道你必須忽略'src'標籤中的圖像並考慮're:xxxxx'標籤中的圖像?是否有任何背後的邏輯?如果是這樣,那將有助於製作通過代碼決定... –

+0

嚴,沒有邏輯背後的。也許在我看來,唯一的辦法是從HTML頁面檢索所有的.jpg,.gif或.png文件。 – xRobot

2

,你可以包括:

foreach ($images as $image) { 
    echo $image->getAttribute('src'); 
    echo $image->getAttribute('rel:image_src'); 
} 
0

$url = ANY URL HERE; 
$html = @file_get_contents($url,false,$context); 
$dom = new domDocument; 
@$dom->loadHTML($html); 
$dom->preserveWhiteSpace = false; 
$images = $dom->getElementsByTagName('img'); 

foreach ($images as $image) { 
    if ($image->hasAttribute('rel:image_src') 
    { 
    echo $image->getAttribute('rel:image_src'); 
    } 
    else 
    { 
    echo $image->getAttribute('src'); 
    } 

} 
+0

問題是,有時候是rel:image_src,有時候是rel:ax_image_src,有時候是si rel:img_src等等,所以有不一樣的屬性。所以這樣就不會工作:( – xRobot

相關問題