Adding Random Content using PHP

One of the things I wanted to add to my site was the ability to have a Random Weather Faq section on many of the pages.

As the vistor goes to the page, at the bottom is a section called Random Weather Facts…

I accomplished with a PHP script, a flat text file with the facts in it and an entry on the web page to call it.

The PHP Script

The script is pretty simple… I grabbed it from a fortune site that had grabed it from elsewhere… I modified it slightly but basically it is the same:

<!--	Get Facts PHP Script -->
<?php
	$f_name = ("facts.txt");
	$fp = fopen($f_name,"r");
	$f_content= fread($fp, filesize($f_name));
	$facts = explode(":::",$f_content);
	fclose($fp);

	// RANDOMIZE 
	shuffle($facts);
	
	// CONFIGURE GENERATOR
	$i=0;
	$max=1;

	// GENERATOR
	while(list(, $code) = each($facts)) {
		if ($i>=$max) { 
			break; 
		}
	// FORTUNE PROCCESSOR
		echo $code;
	// END OF PROCCESSOR
		$i++;
	}
?>
<!--	END GetFacts PHP Script -->

Basically it opens a file called facts.txt, loads all the content into arrays separated by ::: and then randomly picks one of them and echos out the info.

The facts.txt file looks like:

In Arizona, typically, the heaviest rain falls during the summer thunderstorm season, or Monsoon, in our state. The rain can accumulate very quickly, resulting in flooded streets or washes, and can even cause deaths via flash flooding. In Phoenix, the greatest rainfall in a 24 hour period was 4.98 inches on July 1-2, 1911. This total is quite a bit less than the Arizona record of 11.4 inches, which fell on Workman Creek (near Globe) on September 4-5, 1970.:::
Although Phoenix residents may feel that their city MUST be the hottest place around at times, top honors go to Lake Havasu City, where the mercury climbed to 128

I have tried using your script and everything is printed from the facts.txt file. I renamed the file wxfact.txt as well as in the php code.

If I input the direct http://www.k3jae.com/get-facts.php or input it on a page using:


<div class="text" style="float: middle; color: #044703; text-align: justify; padding: 0px 5px 5px 5px; border: 1px ridge rgb(3,80,9); background-color: #A7EC94">
	<h1>Interesting Weather Facts</h1>
	<p> include("get-facts.php"); ?></p>
</div>

EVERY fact in the fact file prints, not just one randomly. Is the flat file limited to a specific amount of facts allowed?

If you only want to display one message, and not a series of messages, why not just use a random number to point to one element of the array? Seems like a lot of code to get there :?

Thanks ever so much Kevin, its working brilliantly, just need to add my own facts now

Would be more code to create the array it would seem. A few others have the code, as written working. Not sure why mine is not.

The array is already being created here:

$facts = explode(“:::”,$f_content);

I’m not criticizing it, we amateurs look to the pros like Kevin to understand how this stuff works.

All i can say is i copied Kevin’s instructions to the T, files names the lot, the only
difference being the facts themselves and the box there enclosed in thats all, the
rest is identical…

And I did same… I think… :roll: I will go back through it and make sure i did not overlook something.

You did say you changed the filename, i didnt even do that, my txt is called fact.txt
the script is called get-facts.php and i used

<p><?php include("get-facts.php"); ?></p>

to include it on my index…

Perhaps you have an error in the wxfact.txt

I didnt use
i used
in the facts.txt not sure it its a problem?

Looking at your php and your txt it does look like it could be the
, try
instead?

<!--	Get Facts PHP Script -->
<?php
	$f_name = ("facts.txt");
	$fp = fopen($f_name,"r");
	$f_content= fread($fp, filesize($f_name));
	$facts = explode(":::",$f_content);
	fclose($fp);

//Get a random fact

echo($facts[rand(0,count($facts)-1)]);

?>
<!--	END GetFacts PHP Script -->

I resolved my issue. I added something to the get-facts.php file with commenting out “instructions” and when that was removed, all works now.

Not understanding why adding “comments” to the PHP file caused that but having said that… all is well now. :smiley:

Great script you can display random almost anything including images if each is terminated with the ::: (except last item)

MAny Thanks now to generate some stuff to use with it

Nice one, glad you got it sorted :slight_smile:

Why not the last one? In Kevin’s example h has the last one set with ::: so thats what i have done
What problem with it cause, could it cause a black output, cause i do get that, rarely but i do?

Man that is an old hunk of code. I posted that in 2005. Works, though I changed it long ago so that the data file could be more consistent by every entry having the delimiter at the end (including the last line).

It is much simpler code:

<?php
############################################################################
# A Project of TNET Services, Inc.
############################################################################
#
#   Project:    TNET Weather Station Pages
#   Module:     random.php
#   Purpose:    Obtains a random entry from a text file containing records
#               deliminted by :::
#
#               Note that EVERY entry needs to end in :::
#
#   Authors:    Kevin W. Reed <[email protected]>
#               TNET Services, Inc.
#
#   Copyright:  (c) 1992-2008 Copyright TNET Services, Inc.
############################################################################
# Configuration
############################################################################
$FileName       = "filename.txt";
############################################################################

if ( file_exists($FileName) ) {

    // Get content as an array
    $contents = explode(":::",file_get_contents($FileName));
    
    // Remove last blank entry
    unset($contents[count($contents) - 1]);

    // Randomize the content
    shuffle($contents);
    
    // Output First Entry
    echo $contents[0];
}
?>

Basically what it does is if the file exists, it explodes into an array delimiting on the ::: delimiter the contents of the file, it then counts the number of records and removes the last one (would be blank), uses shuffle to randomize the data and outputs the first entry.

There is no need for a loop since it only takes the first entry.

If the file does not exist, it outputs nothing.

I added comments to the code as it had none.

Same code without the comments:

$FileName = "filename.txt";
if ( file_exists($FileName) ) {
    $contents = explode(":::",file_get_contents($FileName));
    unset($contents[count($contents) - 1]);
    shuffle($contents);
    echo $contents[0];
}

I have a similar script that does the same thing with XML data.

Hi Kevin

I have used your script a long time - im interesed in the xml code.

Thanks.

Best regards,

Henrik

Okay…

This basically does the same thing but reads an XML version of the data instead.

<?php
############################################################################
# A Project of TNET Services, Inc.
############################################################################
#
#   Project:    TNET Weather Station Pages
#   Module:     randomxml.php
#   Purpose:    Reads an xml formatted file and outputs randomly an entry
#               from it.
#   
#   XML FORMAT:
#
#   <facts>
#       <item>
#           <title>Title of entry</title>
#           <desc><![CDATA[..description goes here...]]></desc>
#       </item>
#       <item> ...
#       </item>
#   </facts>
#
#   Authors:    Kevin W. Reed <[email protected]>
#               TNET Services, Inc.
#
#   Copyright:  (c) 1992-2009 Copyright TNET Services, Inc.
############################################################################
# Configuration
############################################################################
$FileName       = "filename.xml";
############################################################################

if ( file_exists($FileName) ) {
    
    $facts = simplexml_load_file($FileName);

    // Place the data into an array... 
    $contents = array();
    $factcnt = 0;
    foreach($facts->item as $value) {
        $contents[$factcnt][0] = $value->title;
        $contents[$factcnt][1] = $value->desc;
        $factcnt++;
    }
    
    shuffle($contents);
    
    echo "<strong>" . $contents[0][0] . "</strong>
";
    echo $contents[0][1];
}
?>

Example of an XML file it uses: http://www.tnetweather.com/facts.xml

Example of the script in use http://www.tnetweather.com/test/randomxml.php

The use of [color=red][b]<![CDATA[[/b][/color] ... [color=red][b]]]>[/b][/color] in the desc fields prevents the XML parser from trying to parse the contents of the description so that it can contain data that is not valid in an XML file. Otherwise it would fail on some browsers stating it contains invalid data.

Hi Kevin

Thank you very much - nice to have something new to play with when I get home from work.

Best regards,

Henrik

HI Kevin

Thanks for both scripts, I think i will switch to the xml version purely for ease of adding more facts
what i mean is, with the text format it can be a little harder more so when adding multiple facts
trying to find the end to add the ::: and making sure thats no spaces, I use word wrap on notepad
and it gets a bit confusing, this is in no way putting it down, this is just me, hence it will be a lot
easier for me to use the xml version :slight_smile:

Thanks again, i appreciate the release…

Hi again Kevin

I have it up and running now - but I see some problems with the Danish letters

Hi again

Found the solution: