index.html:
HTML Code:
<!DOCTYPE html>
<html>
<head>
<title></title>
<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">
jQuery(function($){
$.get('xml_parse.php', function(data){
$('#my_div').html(data);
});
});
</script>
</head>
<body>
Hi
<div id="my_div">
</div>
</body>
</html>
xml_parse.php:
PHP Code:
<?php
$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)) {
continue;
}
$arrData[$index] = $value;
}
}
return $arrData;
}
$xmlStr = file_get_contents($xmlUrl);
$xmlObj = simplexml_load_string($xmlStr);
$arrXml = objectsIntoArray($xmlObj);
$input = $arrXml['file'];
shuffle($input);
echo file_get_contents($input[0]);
?>
list.xml:
Code:
<files>
<file>file_01.html</file>
<file>file_02.html</file>
<file>file_03.html</file>
<file>file_04.html</file>
</files>
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.
Bookmarks