In the first part of this tutorial we looked at how to set up a generic XML document with image information and then link your page to it through the simpleXML function in php. Using this method it is easy then to exploit the information in the XML document to display rows of thumbnails and even dynamically link them to the full sized images.
What I want to show you now is my way of setting up a pseudo-random function to pick 6 images from the XML document and display them like I have in the side bar to my right. It may seem a little unorthodox to some but I came up with this method to ensure that the sample of 6 is not only random but also that the same image is not displayed twice.
I’ll start with the same simpleXML connection script as we used in the first tutorial:
<?php
// set the XML file name as a PHP string
$myPhotoList = “gallery/photos.xml” ;
// load the XML file
$xml = @simplexml_load_file($myPhotoList) or
die (”no file loaded”) ;
?>
Lets Get Random
Now I want to start adding some code to define the range of image numbers. I also want to create the first ‘random’ number using the rand(firstNumber, lastNumber) function which picks a mathematically random number in the range given. Unfortunately to-date I have been unable to find a built-in function to calculate the number of nodes in an XML document so I’ll be setting the minimum number and the maximum number of images in the xml document manually. This means that the dynamic advantage of only updating the XML document to add more images is greatly decreased since you will also need to change in the php the range of images your working from. Stay tuned for a re-working of this solutions portion of the code.
<?php
…
$min = 0;
$max = 39; //the number of pictures in the xml
$num = rand($min, $max);
?>
