Talk to me about anything. If you’d like to work with me, or
even if you just need a hug, I’ll get back to you shortly.

Please enter your name

Please enter a valid e-mail

It's cold!

Say something!

Display Random Dynamic Content With PHP and XML

Every developer, at one point in time, will run into a situation where they need to display a small amount of dynamic data. Why create a whole database? Enter the magical world of XML. XML is easily manageable by anyone who has ever even dabbled a bit in HTML, so understanding should come easily just by looking at an XML file. PHP has classes already set up to parse XML. Here you’ll learn how to use PHP and XML to randomly generate HTML content.

For our example, we have index.php which includes all of the necessary PHP to parse the XML file and generate the content for the viewer. An images folder has 6 images in it, which are referenced in the XML file, home.xml. Let’s start with the XML file, and how to set it up. If you are viewing the demo, just refresh the page and you’ll see different content every time.

  
<homepage>
	<featured>
		<picture>1.jpg</picture>
		<name>Title 1</name>
		<description>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</description>
	</featured>
</homepage>

So, with XML, every item has to have an opening and closing tag. In our example, we will be creating content from each ‘featured’ block, so you can add as many of these as you like as long as you keep the format the same. Our test XML file just has 6 of these to use. Now, for our PHP, let’s just look at a few lines at a time.

$xml_file = "home.xml";
$xml_picture_key = "*HOMEPAGE*FEATURED*PICTURE";
$xml_name_key = "*HOMEPAGE*FEATURED*NAME";
$xml_description_key = "*HOMEPAGE*FEATURED*DESCRIPTION";

Here we are setting up some variables to tell our script where the XML file is located, as well as how to correctly parse the file. You should create a new variable for each new item you add within the featured blocks.

    function startTag($parser, $data){
        global $current_tag;
        $current_tag .= "*$data";
    }

    function endTag($parser, $data){
        global $current_tag;
        $tag_key = strrpos($current_tag, '*');
        $current_tag = substr($current_tag, 0, $tag_key);
    }

    function contents($parser, $data){
        global $current_tag, $xml_picture_key, $xml_name_key, $xml_description_key, $counter, $featured_array;
        switch($current_tag){
            case $xml_picture_key:
                $featured_array[$counter]->picture = $data;
                break;
            case $xml_name_key:
                $featured_array[$counter]->name = $data;
                break;
            case $xml_description_key:
                $featured_array[$counter]->description = $data;
                $counter++;
                break;
        }
    }

Here we create 3 functions, one to tell the script what to put before the content, one after, and the function to tell it which content block to use. The only thing you’d have to change in this section to apply it to your own work is to add or change each case for each new content in the XML file.

$xml_parser = xml_parser_create();
xml_set_element_handler($xml_parser, "startTag", "endTag");
xml_set_character_data_handler($xml_parser, "contents");

Creating the parser and setting the start tage, end tag, and data handlers. The arguments are the functions that we created earlier.

$fp = fopen($xml_file, "r") or die("Could not open file");
$data = fread($fp, filesize($xml_file)) or die("Could not read file");

Basic PHP file handling functions, that also determine the response if the file is inaccessible

if(!(xml_parse($xml_parser, $data, feof($fp)))){
    die("Error on line " . xml_get_current_line_number($xml_parser));
}

This is the key PHP function that we’re using to parse the file, and if it has an issue it will let you know the line number of the XML file where the problem occurred.

for($y=0;$y<=3;$y++){
    $featured_array = array_values($featured_array);
    $arrayamt = (count($featured_array)-1);
    $x = rand(0,$arrayamt);
    
    echo "<li>";
    echo "<img src='images/" . $featured_array[$x]->picture . "' width='50' height='50' alt='' />";
    echo "<strong>" . $featured_array[$x]->name . "</strong> &nbsp;&nbsp;";
    echo $featured_array[$x]->description;
    echo "</li>";

    unset($featured_array[$x]);
}

Here is where you will do the majority of customizing to suit your needs. Before this, we had all of the data parsed, placed into an array, and ready to be put somewhere, so that’s what we’re doing now. In our example, we will be generating 4 random list items with content from the XML file.

for($y=0;$y<=3;$y++){
    $featured_array = array_values($featured_array);
    $arrayamt = (count($featured_array)-1);
    $x = rand(0,$arrayamt);

First start a ‘for’ loop. the number 3 is significant because we are starting from 0, since arrays start from 0, and we want to generate 4 random items. Second, array_values() is re-indexing our array each time so that when we remove the current item from the array, we have no holes in our array which prevents the loop from spitting out an empty entry. Next we create a varible that determines the length of the array, so we know how large of a number we can randomly generate. Lastly, we choose a random value from our array between 0 and $arrayamt.

echo "<li>";
echo "<img src='images/" . $featured_array[$x]->picture . "' width='50' height='50' alt='' />";
echo "<strong>" . $featured_array[$x]->name . "</strong> &nbsp;&nbsp;";
echo $featured_array[$x]->description;
echo "</li>";

Here you can figure out where you want to place each item. X is used to determine which number of the array you are getting content from. Follow this format when doing your own work and you should be fine.

    unset($featured_array[$x]);
}

Lastly! We remove the value from the array that we just used with unset(), ensuring that we will not use that same value again the next time the loop runs through. Thanks to Richard for the inspiration on this change.

That’s the end! If you have any questions as usual please leave them in the comments. Thanks to kirupa for providing a tutorial that helped me get started on XML parsing with PHP.

25 Comments
  1. Another great post Joren. Many situations where this could be useful.

  2. And, BTW your RSS feeds in’t working ;)

    • Joren Rapini says:

      Thanks for the heads up! I’m not sure what is going on, it must be an issue with feedburner. My feed is broken when I open it in Brief, but it works fine in Google Reader. There are about 5 other feeds in my Brief that are having the same problem, so I’ll keep looking into it.

  3. Mike says:

    Hi Joren,

    Thanks for showing me this, I got it working but want to make the or any of the other info inside it – a link to a different url. Could you possibly tell me what I would need to add to the XML and the PHP?

    Thanks Again

    Mike

  4. Mike says:

    Sorry, forgot it wouldn’t show code. I want to make the list element or anything inside it, a link to a url. Please help..

    • Joren Rapini says:

      Hey Mike, it should be relatively easy to follow the pattern that I laid out here. Just add another item to the XML file within ‘featured’, and then add a variable for that data in all the places that I went over, and then you can add it within the echo commands.

  5. Richard says:

    Nice Tutorial,

    Another method is to load the random things in an array, take a random thing, then delete it from the array ie. no checking for duplicates

    • Joren Rapini says:

      Awesome! You are very right. I don’t know why I didn’t think to do that before. Use unset() to remove the value $x from the array at the end of the loop, and then at the beginning of the loop reindex the array with array_values() since there is now a hole in it thanks to the unset. This allows for less code, and you no longer have to create new rules depending on the amount of times the loop repeats. All you have to do now is change the maximum number in the for loop.

      • Houston says:

        Joren,

        I’m very new to PHP and XML. Can you write a version 2 of this tutorial using Richard’s suggestion? It would be much appreciated by amateurs like myself!

      • Joren Rapini says:

        Houston, you’re already looking at it. The article as is was updated months ago with what I talked about in these comments.

  6. Andrew says:

    Many thanks for this – I’m no PHP programmer but I managed to tweak this and it will be on out new video production website soon!

  7. I agree with all your data and can hungrily look onward to the subsequent messages. Only expressing cheers will not just end up being enough, for your extraordinary readability with your writing. I’ll immediately grab your rss feed to stay privy with all posts. Good job and much success in your internet business endeavors! Whatwhat!

  8. Aubrey Ross says:

    Awesome! You are very right. I don’t know why I didn’t think to do that before. Use unset() to remove the value $x from the array at the end of the loop, and then at the beginning of the loop reindex the array with array_values() since there is now a hole in it thanks to the unset. This allows for less code, and you no longer have to create new rules depending on the amount of times the loop repeats. All you have to do now is change the maximum number in the for loop.
    +1

  9. Andrea says:

    Thanks Joren, we use php on our website and are looking to expand our dynamic offering – so this stuff is really, really useful.

  10. Mihai says:

    Thank you very much Joren for your post. It helped me alot.

  11. Scott says:

    Thanks for this Joren. I have been looking for something like this for our video production website and will put it into effect.

    Cheers!

  12. Seotons says:

    Thanks for this tutorial, it is exactly what I needed!

  13. Ethel Stieff says:

    Invaluable content material! I have been actually worrying is that there’s additional info to a group of bad your query, however mainly my personal trade of views. Thanks for a beautiful release.

  14. Jimbeeer says:

    Great tutorial. Very easy to follow.

    Just one thing though.

    When I put a carriage return in the description, it only takes the second sentence. I tried putting a in there instead but it’s still doing the same. Any ideas?

  15. Jimbeeer says:

    the comments stripped out my html code.

    I tried putting in a (open chevron) br/ (close chevron)

  16. Fernanda N says:

    thank you very much!
    i was looking for something like this for ages!
    it worked perfectly! ;)

  17. Jothi says:

    Great resource!

  18. Scott says:

    When running the demo in my environment, I get an error: Creating default object from empty value… It skips the first XML node but displays everything else. Any ideas?

Leave a Reply


This site is protected by Comment SPAM Wiper.