Get image source from html dom element

2019-06-04 06:57发布

I am querying image using getElementsByTagName("img") and printing it using image->src , it does not work. I also tried to use image->nodeValue this to does not work.

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
}

1条回答
【Aperson】
2楼-- · 2019-06-04 07:25

Okay, use this to display your image:

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

and it will surely display your image. Make sure path to the image is correct.

查看更多
登录 后发表回答