Search code examples
phpurlforeachsimple-html-dom

Duplicate PHP Code Block


I get images from a specific url. with this script im able to display them on my website without any problems. the website i get the images from has more than one (about 200) pages that i need the images from.

I dont want to copy the block of PHP code manually and fill in the page number every time from 1 to 200. Is it possible to do it in one block?

Like: $html = file_get_html('http://example.com/page/1...to...200');

   <?php

require_once('simple_html_dom.php');
$html = file_get_html('http://example.com/page/1');
foreach($html->find('img') as $element) {
    echo '<img src="'.$element->src.'"/>';
}

$html = file_get_html('http://example.com/page/2');
foreach($html->find('img') as $element) {
    echo '<img src="'.$element->src.'"/>';
}

$html = file_get_html('http://example.com/page/3');
foreach($html->find('img') as $element) {
    echo '<img src="'.$element->src.'"/>';
}
?>

Solution

  • You can use a for loop like so:

    require_once('simple_html_dom.php');
    for($i = 1; $i <= 200; $i++){
        $html = file_get_html('http://example.com/page/'.$i);
        foreach($html->find('img') as $element) {
            echo '<img src="'.$element->src.'"/>';
        }
    }
    

    So now you have one block of code, that will execute 200 times.

    It changes the page number by appending the value of $i to the url, and every time the loop completes a round, the value of $i becomes $i + 1.

    if you wish to start on a higher page number, you can just change the value of $i = 1 to $i = 2 or any other number, and you can change the 200 to whatever the max is for your case.