How to Load Random Flickr Images with PHP

This isn’t rocket science, but I did search Google extensively before building my own script.  Save the script as Random_Flickr_Image.php (or whatever) and reference it in your img tag.  For example, <img src=”/images/Random_Flickr_Image.php”/>.


<?php
$doc = new DOMDocument();
@$doc->loadHTMLFile("http://www.flickr.com/explore/interesting/7days/");
$xpath = new DOMXpath($doc);
if($xpath){
   $url = $xpath->query("//td[@class='Photo']/span/a/@href");

   @$doc->loadHTMLFile("http://www.flickr.com".$url->item(0)->nodeValue);
   $xpath = new DOMXpath($doc);

   if($xpath){
      $url = $xpath->query("//div[@class='photoImgDiv']/img/@src");
      $im = @imagecreatefromjpeg($url->item(0)->nodeValue);
      if($im){
         header('content-type: image/jpeg');
         imagejpeg($im);
      }else
         echo "error";
   }
}
?>
You can leave a response, or trackback from your own site.

5 Responses to “How to Load Random Flickr Images with PHP”

  1. Nice!

    No way to get them bigger than the 7-days page preview, I guess?

  2. Jamie says:

    I’m positive that there’s a better way that gets the larger sizes. I didn’t play around with it long enough to figure that out. But at the very least, you could load the page that the thumbnail points to and then screenscrape the image url. Probably just a few more lines of code.

  3. Jamie says:

    I just tried a couple of things out. Without logging in to Flickr, it doesn’t look like you can see the magnifying glass on the pages and view larger images. However, I did find that the <div> on the page with class=”photoImgDiv” had a larger image than the one in the 7-day preview.
    I’ve changed the code to use that version instead of the smaller thumb.

  4. [...] I have yet to solve a puzzle. Link to PHP Code to load random Flickr images. Posted in javascript | Tags: Canvas Tag, coding fun, HTML5, javascript, php, Random Flickr [...]

  5. [...] It simply fetches images from the flickr’s random “interesting photos from the last 7 days” using this function (derived from this post): [...]

Leave a Reply