PHP How to get only the first image after a getimagesize judgement

213 views Asked by At

I use simple_html_dom and url_to_absolute get all the image from one site. but after a getimagesize judgement, how to echo only the first image? not the all? Thanks.

<?php
set_time_limit(0);
require_once('simple_html_dom.php');
require_once('url_to_absolute.php');

$url = 'http://matthewjamestaylor.com/blog/how-to-post-forms-to-clean-rewritten-urls';

$html = file_get_html($url);

foreach($html->find('img') as $element) {
    $src= url_to_absolute($url, $element->src);//get http:// imgaes

    if(preg_match('/\.(jpg|png|gif)/i',$src)){
    $arr = getimagesize($src);

        if ($arr[0] >= 100 and $arr[1] >= 100) { //width and height over 100px
            echo '<img src="'.$src.'" />'; // in here ,how to echo only the first image? not the all?
        }

    }

}

?>
2

There are 2 answers

0
Matej Baćo On BEST ANSWER

Break foreach loop after first image:

if ($arr[0] >= 100 and $arr[1] >= 100) { 
   echo '<img src="'.$src.'" />'; 
   break;
}

More on break.

0
NoBBy On

It looks like that, simple_html_dom supports getting the Nth element. If you really only need the first image, just use:

$html->find('img', 0)