2013-04-17 104 views
1

我使用getElementsByTagName("img")查詢圖像並使用image->src進行打印,但它不起作用。我也嘗試使用image->nodeValue這不起作用。從html dom元素獲取圖像源

require('simple_html_dom.php'); 

$dom=new DOMDocument(); 
$dom->loadHTML($str);  /*$str contains html output */ 

$xpath=new DOMXPath($dom); 
$imgfind=$dom->getElementsByTagName('img'); /*finding elements by tag name img*/ 

foreach($imgfind as $im) 
{ 
    echo $im->src;  /*this doesnt work */ 
    /*echo $im->nodeValue; and also this doesnt work (i tried both of them    separately ,Neither of them worked)*/ 

    // echo "<img src=".$im->nodeValue."</img><br>"; //This also did not work 
} 

/*the image is encolsed within div tags.so i tried to query value of div and print but still image was not printed*/ 

$printimage=$xpath->query('//div[@class="abc"]'); 
foreach($printimage as $image) 
{ 
    echo $image->src; //still i could not accomplish my task 
} 
+0

嗯......你能減少那個頭銜的長度嗎? –

+0

您是否試過'var_dump($ imgfind);' –

+1

使用'echo $ im-> getAttribute('src');'而不是'echo $ im-> src;' – saveATcode

回答

6

好了,用它來顯示您的圖片:

foreach($imgfind as $im) 
{ 
    echo "<img src=".$im->getAttribute('src')."/>"; //use this instead of echo $im->src; 
} 

,它一定會顯示您的影像。 確保圖像路徑正確

+0

,感謝代碼的工作,我對你的代碼做了一個小小的修改,即在echo「 getAttribute('src')。「/>」;(它認爲圖像是一個沒有空間的目錄..其他地方它的完美無瑕,感謝很多朋友。 – sujai

+0

很棒!!!!! !!!!! – saveATcode