View Full Version : Load an random external HTML into a Div

10-17-2010, 09:50 AM
Hi people, I would like to make the following thing:
Load a random file, from a xml list, into a div. I've made a scheme where I show what I was trying to make, but I don't know how to make it.


I would like to load into a div a random HTML file, loaded from a XML. Does anyone knows an similar example or can tell me how's possible to do this, please? is it better to do with Javascript ?

thanks for the attention guys

10-17-2010, 11:53 AM

<!DOCTYPE html>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>
<script type="text/javascript">
$.get('xml_parse.php', function(data){
<div id="my_div">



$xmlUrl = "list.xml"; // XML file URL
function objectsIntoArray($arrObjData, $arrSkipIndices = array())
$arrData = array();

// if input is object, convert into array
if (is_object($arrObjData)) {
$arrObjData = get_object_vars($arrObjData);

if (is_array($arrObjData)) {
foreach ($arrObjData as $index => $value) {
if (is_object($value) || is_array($value)) {
$value = objectsIntoArray($value, $arrSkipIndices); // recursive call
if (in_array($index, $arrSkipIndices)) {
$arrData[$index] = $value;
return $arrData;
$xmlStr = file_get_contents($xmlUrl);
$xmlObj = simplexml_load_string($xmlStr);
$arrXml = objectsIntoArray($xmlObj);
$input = $arrXml['file'];
echo file_get_contents($input[0]);



Notes: Make sure all the files listed in list.xml exist. Paths, if any in these files (file_01.html, file_02.html, etc.) should be valid for index.html.

This could also be done entirely with javascript. But PHP has a better randomization algorithm, so I chose to use it.

If index.html were to be index.php, this could all be done using PHP, which might be a good idea, folks often have javascript disabled.

Using the method in this post though, with slight modification, would allow you to setup a slideshow of the contents, or provide a link or button to update the contents on the fly. However, at that rate the randomness should probably only be applied once per page (index page) load.

10-17-2010, 06:24 PM
Thank you very much for the reply. It's great. I'm not being able to make it work yet don't know very well why. Perhaps due to a incompatibility somewhere. It doesn't read me a JS effects I have in the html file :(

but what you explained is perfect, I've made a simple example with your explanation and it worked very well. Thanks again

10-17-2010, 06:50 PM
If it is a javascript problem, just give me a link to a live demo of the page and I can figure it out. Even if it's more than that, I may get a clue. So if you want more help:

Please post a link to a page on your site that contains the problematic code so we can check it out.