user1515503
user1515503

Reputation: 71

filter images from webpage based on size

i want to list all images from any particular webpage but want to list only those images whose size is biggger than 10kb .i am using this code to list the images which lists all images of that particular page but i dont want to list images whose size is less than 10 kb

$url="http://example.com";

$html = file_get_contents($url);

$doc = new DOMDocument();
@$doc->loadHTML($html);

$tags = $doc->getElementsByTagName('img');

foreach ($tags as $tag) {
   echo $tag->getAttribute('src');
}

Upvotes: 1

Views: 176

Answers (2)

citruspi
citruspi

Reputation: 6891

PHP has a filesize() function which returns the size in bytes and would be used as such:

echo "The file size in KB is ".(filesize('image.png')/1024);

The only problem is that it doesn't work with remote files.

So, you could:

  1. Save each image to a temporary directory
  2. Iterate through them and check the filesize
  3. If the size is <10, delete it
  4. List the remaining images

Edit

As Blowski has pointed out, as of PHP 5.0, it will work with some URL wrappers, so you should be fine.

Edit 2

Some sample code:

foreach ($tags as $tag) {
   if (file_exists($tag->getAttribute('src')) && filesize($tag->getAttribute('src')) >= 10240)
     echo $src;
   }
}

Edit 3

I did some more research, and found that stat is not supported by the HTTP(S) protocol. Therefore, you must save the file to your own server for it to work.

Edit 4

Solution using get_headers() approach instead of filesize().

foreach ($tags as $tag) {
   $data = get_headers($tag->getAttribute('src'));
   if(($data["Content-Length"]/1024)>=10){
     echo $src;
   }
}

Upvotes: 2

Abid Hussain
Abid Hussain

Reputation: 7762

Try this:-

$img = get_headers("http://static.adzerk.net/Advertisers/2564.jpg", 1);
$imgbit = $img["Content-Length"]/1024;

echo "The file size in KB is ".$imgbit;

Upvotes: 2

Related Questions