0

I'm using Simple HTML DOM to get a certain element like this:

foreach($html->find('img') as $d) { 
 echo $d->outertext;
}

This will echo all the images. Let's say for example I only need image with index (meaning relative to all images) number 3,7,14 and > 15. Is there a way to do something this complicated?

Youss
  • 4,196
  • 12
  • 55
  • 109

3 Answers3

1

Probably the simplest way is to add all the img tags to an array, and from there you can extract them according to index number.

ygesher
  • 1,133
  • 12
  • 26
  • The problem is extraction, how do I do that in an efficient way without repeating the code? – Youss Jul 28 '13 at 09:31
1

find returns an array so just use the index

$imgs =$html->find('img');

$imgs[3];
$imgs[7];
$imgs[14];

for($i=15;$i<count($imgs);$i++){
  $imgs[$i];
}
Patrick Evans
  • 41,991
  • 6
  • 74
  • 87
  • `$imgs =$html->find('img'); $imgs[3]; $imgs[7]; $imgs[14]; for($i=15;$ifind($imgs) as $d) { echo $d->outertext; }` ..........nothing – Youss Jul 28 '13 at 09:46
  • Look at the documentation on how the elements work, the array is an array of objects you have to use whatever mechanism the library uses to get the actual data. – Patrick Evans Jul 28 '13 at 09:46
  • and does it actually find any imgs? if $imgs ends up being empty you havent found any img tags to begin with. – Patrick Evans Jul 28 '13 at 09:50
  • This is the website http://www.nu.nl/ There are plenty of images. I can call them using the code in my answer, but implementing your code just doesn't work – Youss Jul 28 '13 at 09:51
  • you dont just copy and paste my code, you have to tailor it for your code, and it doesnt just go above your old code, its just showing you how you would access the array. you have to actually use the array elements in some way. – Patrick Evans Jul 28 '13 at 09:56
1

You can accomplish this with a $count variable and in_array(). Declare the count variable before the loop, and declare the array of the required IDs. And in the loop, you can use an if statement to check if the image ID is in the array or greater than 15.

$count = 1;
$ids = array(3, 7, 14);

foreach($html->find('img') as $d) { 
if(in_array($count, $ids) || $count > 15){

 echo $d->outertext;
 $count++;    

}

Hope this helps!

Amal Murali
  • 75,622
  • 18
  • 128
  • 150