Fetching all images src from specific div

故事扮演 提交于 2019-12-24 16:56:02

问题


Suppose, I have HTML structure like:

 <div>
      <div class="content">
           <p>This is dummy text</p>
           <p><img src="a.jpg"></p>
           <p>This is dummy text</p>
           <p><img src="b.jpg"></p>
      </div>
 </div>

I want to fetch all image src from .content div. I tried :

 <?php
 // a new dom object
 $dom = new domDocument; 

 // load the html into the object
 $dom->loadHTML("example.com/article/2345"); 

 // discard white space
 $dom->preserveWhiteSpace = false;
 //get element by class
 $finder = new DomXPath($dom);
 $classname = 'content';
 $content = $finder->query("//*[contains(@class, '$classname')]");
 foreach($content as $item){
    echo $item->nodevalue;
 }

But, I cannot get anything when I loop through $content. PLease Help.


回答1:


Change your XPath query as shown below:

// loading html content from remote url
$html = file_get_contents("http://nepalpati.com/entertainment/22577/");
@$dom->loadHTML($html);  
...
$classname = 'content';
$img_sources = [];

// getting all images within div with class "content"
$content = $finder->query("//div[@class='$classname']/p/img");
foreach ($content as $img) {
    $img_sources[] = $img->getAttribute('src');
}
...
var_dump($img_sources);
// the output:

array(2) {
  [0]=>
  string(68) "http://nepalpati.com/mediastorage/images/2072/Falgun/khole-selfi.jpg"
  [1]=>
  string(72) "http://nepalpati.com/mediastorage/images/2072/Falgun/khole-hot-selfi.jpg"
}


来源:https://stackoverflow.com/questions/35646107/fetching-all-images-src-from-specific-div

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!