Forum Moderators: coopster

Message Too Old, No Replies

Loading HTML file dynamically

         

junnydc

8:10 am on Nov 15, 2011 (gmt 0)

10+ Year Member



Hi,
I want to dynamically load a html file to my site. How can I achieve this.

Example. on the same directory I have 3 files with some code inside.

file1.html
file2.html
file3.html


on my footer.php I want to show the content of file(x).html.
"X" is a random number from 1 to 3.

Many thanks for the help.

penders

9:13 am on Nov 15, 2011 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



Somewhere in footer.php you can simply include [php.net] the required file...

<?php include "file{$x}.html"; ?>


Where $x is your random number.

SteveWh

12:33 am on Nov 17, 2011 (gmt 0)

10+ Year Member



Expanding to the complete code, I think this should do it:

<?php 
$x = mt_rand(1,3);
include "file{$x}.html";
?>

Or this

<?php 
$x = "file" . mt_rand(1,3) . ".html";
include $x;
?>

Hm... or this?

<?php 
include "file" . mt_rand(1,3) . ".html";
?>

penders

9:34 am on Nov 17, 2011 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



Yes, any of those should work. The method you choose could depend on whether you had any more plans for your script. If, for instance, you wanted to store your random number in a cookie in order to remember it for an hour or so (so the user would be presented with the same page until the cookie expired, etc.)? In that respect #1 is the most flexible (and easiest to read IMO). I would tend not to use #2 (unless you needed to know later the name of the file included). And #3 is good if this is literally all you want to do (and it doesn't pollute the global scope with a variable).

<?php include 'file'.mt_rand(1,3).'.html' ?>


This doesn't really matter (and in some ways is personal preference) but... I would always try to use single quoted strings when you are not using variable parsing [uk3.php.net] (a feature of double quoted strings) - slightly more efficient.