user254153
user254153

Reputation: 1883

Fetching all images src from specific div

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.

Upvotes: 1

Views: 2421

Answers (1)

RomanPerekhrest
RomanPerekhrest

Reputation: 92854

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"
}

Upvotes: 4

Related Questions