Jump to content

Archived

This topic is now archived and is closed to further replies.

member

Random Text loader

Recommended Posts

Hi,

I got this piece of code:

-------------------------------------------------------

<?php

// Random Text PHP script by Nate Baldwin, www.mindpalette.com (freeware - use at your own risk) 2004/06/06

[color=red]$MPTextFile = "random.txt"; // path to file with random text
$MPSepString = "*divider*"; // string used to separate into list[/color]
$MPTextToHTML = true; // convert text to HTML entities (if no HTML code in text)

//-------------------------------------------------------------------------------------------------
//  DECLARE AND RUN TEXT IMPORT AND RANDOMIZER SCRIPT
//-------------------------------------------------------------------------------------------------

class MPRandomText {
var $filepath;
var $sepstring;
var $fixchar;
var $textfix;
var $contents;
var $random;
var $errors;
// initiate object and start functions...
function MPRandomText($filepath, $sepstring, $textfix) {
$this->filepath = $filepath;
$this->textfix = $textfix;
$this->sepstring = $sepstring;
$this->errors = "";
$this->contents = "";
$this->FileToString();
}
// read file contents into string variable...
function FileToString() {
@$filePointer = fopen($this->filepath, "r");
if (!$filePointer) $this->errors = "Text file could not be opened.";
if ($this->errors == "") {
$this->contents = fread($filePointer, filesize($this->filepath));
fclose($filePointer);
if (!$this->textfix) $this->HTMLContent();
$this->MakeArray();
}
}
// if importing an HTML page, drop everything outside of (and includeing) the <body> tags...
function HTMLContent() {
$test = stristr($this->contents, "<body");
if ($test !== false) {
$test = stristr($test, ">");
if ($test !== false) {
$test = str_replace("</BODY>", "</body>", $test);
$test = explode("</body>", substr($test, 1));
if (count($test) > 1) $this->contents = $test[0];
}
}
}
// convert the file text into a list using separation character...
function MakeArray() {
$array = explode($this->sepstring, $this->contents);
if (count($array) > 0) {
$this->contents = $array;
$this->CleanTextList();
} else $this->errors = "Text file contents are empty or could not be read.";
}
// clean up the list of empty values and extra white space...
function CleanTextList() {
$result = array();
if (is_array($this->contents)) {
for ($n=0; $n<count($this->contents); $n++) {
$string = trim($this->contents[$n]);
$test = trim($string."test");
if (!empty($string) AND $test != "test") $result[] = $string;
}
if (count($result) > 0) {
$this->contents = $result;
$this->RandomString();
}
}
}
// get random text string from list...
function RandomString() {
reset($this->contents);
srand((double) microtime() * 1000000);
shuffle($this->contents);
$this->random = $this->contents[0];
}
// send finished results to be printed into HTML page...
function GetResults() {
if ($this->errors != "") return $this->errors;
else {
if ($this->textfix == true) $this->random = htmlentities($this->random);
return $this->random;
}
}
}

// create object and write random text into page...
$ThisMPRandom = new MPRandomText($MPTextFile, $MPSepString, $MPTextToHTML);
print($ThisMPRandom->GetResults());

?>

-----------------------------------------------------------------------------------------------

what i want to do is use this .txt file: http://islamcentre.awardspace.com/test/test1.txt
to load up a random text from there. Each Quote starts with "Narrated"
Also I want this part to be ignored:

<><><>1<><><>
<><><>2<><><>
<><><>3<><><>
and so on till infinate.

Can anybody know how to do this?

I am really desperate on how to do this.

Anyhelp is most appreciated.

Thank You Very Much

Note: each quote cannot be put into a new line, as there are thousands of quotes

Share this post


Link to post
Share on other sites
Wow... that's complicated for what you're trying to do.... maybe a script of mine will help you.

[code]
<?php
$quotes = array();

$quotes[] = "All men are alike in their nature, but become different through practice";
$quotes[] = "He that would perfect his work must first sharpen his tools";
$quotes[] = "To see what is right and not to do it, is want of courage";
$quotes[] = "Sorrow not at being unknown, but seek to be worthy of note";
$quotes[] = "To go beyond is as wrong as to fall short";
$quotes[] = "If you have faults, do not fear self-improvement";
$quotes[] = "Study as if you were never to master it; as if in fear of losing it";
$quotes[] = "To love determination and not learning: recklessness";
$quotes[] = "When we see men of a contrary character, we should turn inwards and examine ourselves";
$quotes[] = "You cannot open a book without learning something";
$quotes[] = "Ability will never catch up with the demand for it";
$quotes[] = "Silence is the true friend that never betrays";
$quotes[] = "Everything has beauty but not everyone sees it";
$quotes[] = "Life is really simple, but we insist on making it complicated";
$quotes[] = "What is the sound of one hand clapping?";
$quotes[] = "A journey of a thousand miles begins with a single step";
$quotes[] = "Better a diamond with a flaw than a pebble without";
$quotes[] = "He who speaks without modesty will find it difficult to make his words good";
$quotes[] = "It does not matter how slowly you go, so long as you do not stop";
$quotes[] = "Never give a sword to a man who can't dance";
$quotes[] = "Only the wisest and stupidest of men never change";
$quotes[] = "The cautious seldom err";
$quotes[] = "The superior man understands what is right; the inferior man understands what will sell";
$quotes[] = "To be wronged is nothing unless you continue to remember it";
$quotenum = rand(1,count($quotes));

echo $quotes[$quotenum] . " ~ Confucius";

?>[/code]

I use that on my site to display a random quote... is that what you're looking for?

EDIT: ok, that might not work if you have thousands of lines... but the theory should work the same grabbing them from a file.

Share this post


Link to post
Share on other sites
Thanks, but it will involve me in maually putting in the thousands of quotes, i don't think it is that complicated and it is possible I am sure.



[quote author=ober link=topic=107681.msg432273#msg432273 date=1158005726]
Wow... that's complicated for what you're trying to do.... maybe a script of mine will help you.

[code]
<?php
$quotes = array();

$quotes[] = "All men are alike in their nature, but become different through practice";
$quotes[] = "He that would perfect his work must first sharpen his tools";
$quotes[] = "To see what is right and not to do it, is want of courage";
$quotes[] = "Sorrow not at being unknown, but seek to be worthy of note";
$quotes[] = "To go beyond is as wrong as to fall short";
$quotes[] = "If you have faults, do not fear self-improvement";
$quotes[] = "Study as if you were never to master it; as if in fear of losing it";
$quotes[] = "To love determination and not learning: recklessness";
$quotes[] = "When we see men of a contrary character, we should turn inwards and examine ourselves";
$quotes[] = "You cannot open a book without learning something";
$quotes[] = "Ability will never catch up with the demand for it";
$quotes[] = "Silence is the true friend that never betrays";
$quotes[] = "Everything has beauty but not everyone sees it";
$quotes[] = "Life is really simple, but we insist on making it complicated";
$quotes[] = "What is the sound of one hand clapping?";
$quotes[] = "A journey of a thousand miles begins with a single step";
$quotes[] = "Better a diamond with a flaw than a pebble without";
$quotes[] = "He who speaks without modesty will find it difficult to make his words good";
$quotes[] = "It does not matter how slowly you go, so long as you do not stop";
$quotes[] = "Never give a sword to a man who can't dance";
$quotes[] = "Only the wisest and stupidest of men never change";
$quotes[] = "The cautious seldom err";
$quotes[] = "The superior man understands what is right; the inferior man understands what will sell";
$quotes[] = "To be wronged is nothing unless you continue to remember it";
$quotenum = rand(1,count($quotes));

echo $quotes[$quotenum] . " ~ Confucius";

?>[/code]

I use that on my site to display a random quote... is that what you're looking for?
[/quote]

Share this post


Link to post
Share on other sites
[quote author=member link=topic=107681.msg432304#msg432304 date=1158007759]
anyone can u help?
[/quote]

Share this post


Link to post
Share on other sites
It's a 300kb text file. You're not thinking of reading the entire thing every time you want a quote display from it, surely!

Far far better to have it in a database and select a record at random.  Worst case, manually clean out the <><><>#<><><> things then read the file into an array and then write the array elements back to a database ONCE.

I'm not sure what the script you posted has to do with the problem.

Share this post


Link to post
Share on other sites
It's only 300k it has been broken down to a smaller file size so that it can load up easier. It is originally 4.6MB in file size and I got another 3 more 3MB files to add as well.

I am not going to read it, It is the visitor to my site, What it is is Islamic Reporting from the Prophet's companions and so on, so there's thousands of them.

[quote author=AndyB link=topic=107681.msg432325#msg432325 date=1158010765]
It's a 300kb text file. You're not thinking of reading the entire thing every time you want a quote display from it, surely!

Far far better to have it in a database and select a record at random.  Worst case, manually clean out the <><><>#<><><> things then read the file into an array and then write the array elements back to a database ONCE.

I'm not sure what the script you posted has to do with the problem.
[/quote]

Share this post


Link to post
Share on other sites
A 300 kb text file will take almost two minutes on a dial-up line.  A database selection of a random record will take microseconds.

Are you saying you do not want to use a database for this, or are you saying you don't know how to get the content of a 10Mb text file into 1000+ records in a database.

Share this post


Link to post
Share on other sites
I don't think u understood the question, What I want is a random piece of quote from the .txt to be randomly loaded onto the webpage from the .txt file. A person would not need to load up the .txt file. Only a few lines will be loaded, surely it won't take long to load on a dial up connection.

Plus what do u mean by database? do u mean MySQL?

I am new to php, so I won't understand some stuff, i am 15yrs old, still got time to learn

[quote author=AndyB link=topic=107681.msg432329#msg432329 date=1158011217]
A 300 kb text file will take almost two minutes on a dial-up line.  A database selection of a random record will take microseconds.

Are you saying you do not want to use a database for this, or are you saying you don't know how to get the content of a 10Mb text file into 1000+ records in a database.
[/quote]

Share this post


Link to post
Share on other sites
What everyone is trying to get through to you is that when you view any web page on the internet (ANY WEB PAGE) it is going to download the entire page bits at a time and display them to you as they become available.

What would happen if you had that large of a text file is that the INTERNET would read through the entire file first. 
PHP would put all of those lines into an array.
PHP would choose a random line inside of that array to display to the user.

That is it, end of story.  When reading through a text file the server, php, the internet HAS to read through the file to find the random line.  I know 300k doesn't seem like much on a computer but for some, it's the end of the world when it comes to the internet.

Really, a database is the way to go here.  It's cheap and easy and there are PLENTY of tutorials on how to make this happen.  Three lines of code, really.

Share this post


Link to post
Share on other sites
I understood the question, but my brain wasn't working when I gave the first answer.

A text file is sequential data and as far as I'm aware it's not possible to read a randomly selected/accessed part of the file.  The way in which data are retrieved from a text file is typically to read the entire file into an array and then select a random array element.  Reading the whole file takes time and server processing power, and it would have to be done every time a new visitor wanted to see a page with a random piece of text.  Contrast that to a database where random access is possible - to get the 55th item you just read the 55th record.

I would certainly use a MySQL database for this.

Share this post


Link to post
Share on other sites
Adding on to what AndyB said...

Since you would have to read it everytime anyways you might as well just read it once into a DB, that way you can access it like a million times faster in the future...

Share this post


Link to post
Share on other sites
Here's an example from your original 300kb text file. Guess it's pretty quick :)

http://www.halfadot.com/temp/prophet.php - refresh page for a new random selection

Share this post


Link to post
Share on other sites
Thanks just what I need,
could u provide me the code to test? on my site?

Thank You.

Share this post


Link to post
Share on other sites
Sure ... with help from the wizards in the Regex forum ...

[code]<?php
// next two lines get the server start time for execution
$starttime = explode(' ', microtime());
$starttime = (float)$starttime[1] + (float)$starttime[0];

echo "<a href='". $_SERVER['PHP_SELF']. "'>another saying</a><hr/>"; // refreshes page

// this is the real meat of the script
$sayings = file("allah_says.txt"); // read entire file into an array
$saythis = $sayings[rand(0,count($sayings)-1)]; // select a random array element

// this replaces the <><><>#<><><> delimiters
$saythis = preg_replace('|<><><>[0-9]{1,4}<><><>|', '', $saythis);

echo nl2br($saythis); // output the random saying

// get the server end time for execution and output the time taken
$endtime = explode(' ', microtime());
$endtime = (float)$endtime[1] + (float)$endtime[0];
$totaltime = number_format(($endtime - $starttime), 4, '.', '');
echo "<hr><p>My server generated this page in <font color='red'><strong>$totaltime seconds</strong></font> from a text file with ". count($sayings). " sayings.</p>";
?>[/code]

As you see, it takes around 0.003 seconds to handle the 300kb data file you posted. Predictably it'll take much longer if you use a 10Mb text file - a database would be a far better solution, and easy to create as the code above already shows you how to read the elements of the file into an array and remove the delimiter text between sayings.

Share this post


Link to post
Share on other sites
Thanks so much, u can see it on: http://islamcentre.awardspace.com/test/test.php

I was wondering, what is the code to do this for multiple files?, so it would make loading the quotes faster?
I got more than 1 .txt file.

Thank You.

[quote author=AndyB link=topic=107681.msg432741#msg432741 date=1158071137]
Sure ... with help from the wizards in the Regex forum ...

[code]<?php
// next two lines get the server start time for execution
$starttime = explode(' ', microtime());
$starttime = (float)$starttime[1] + (float)$starttime[0];

echo "<a href='". $_SERVER['PHP_SELF']. "'>another saying</a><hr/>"; // refreshes page

// this is the real meat of the script
$sayings = file("allah_says.txt"); // read entire file into an array
$saythis = $sayings[rand(0,count($sayings)-1)]; // select a random array element

// this replaces the <><><>#<><><> delimiters
$saythis = preg_replace('|<><><>[0-9]{1,4}<><><>|', '', $saythis);

echo nl2br($saythis); // output the random saying

// get the server end time for execution and output the time taken
$endtime = explode(' ', microtime());
$endtime = (float)$endtime[1] + (float)$endtime[0];
$totaltime = number_format(($endtime - $starttime), 4, '.', '');
echo "<hr><p>My server generated this page in <font color='red'><strong>$totaltime seconds</strong></font> from a text file with ". count($sayings). " sayings.</p>";
?>[/code]

As you see, it takes around 0.003 seconds to handle the 300kb data file you posted. Predictably it'll take much longer if you use a 10Mb text file - a database would be a far better solution, and easy to create as the code above already shows you how to read the elements of the file into an array and remove the delimiter text between sayings.
[/quote]

Share this post


Link to post
Share on other sites
Replace:
[code]$sayings = file("allah_says.txt"); // read entire file into an array
$saythis = $sayings[rand(0,count($sayings)-1)]; // select a random array element[/code]

With this:
[code]$list = array("allah_says1.txt", "allah_says2.txt", "allah_says3.txt"); // as many files as you want to have
$thefile = $list[rand(0,count($list)-1)]; // select a random text file
$sayings = file($thefile); // read entire file into an array
$saythis = $sayings[rand(0,count($sayings)-1)]; // select a random array element[/code]

You can add as many filenames to the $list=array( statement and the code will continue to work.

Share this post


Link to post
Share on other sites
thanks So Much!!!!!!!!!! It is just what I was waiting for for months!
lol, saw ur post in the Regex forum, Yeh I am thrilled.

Now all I need to do is to change the font style, size and colour...

Thanks once again

[quote author=AndyB link=topic=107681.msg433604#msg433604 date=1158168337]
Replace:
[code]$sayings = file("allah_says.txt"); // read entire file into an array
$saythis = $sayings[rand(0,count($sayings)-1)]; // select a random array element[/code]

With this:
[code]$list = array("allah_says1.txt", "allah_says2.txt", "allah_says3.txt"); // as many files as you want to have
$thefile = $list[rand(0,count($list)-1)]; // select a random text file
$sayings = file($thefile); // read entire file into an array
$saythis = $sayings[rand(0,count($sayings)-1)]; // select a random array element[/code]

You can add as many filenames to the $list=array( statement and the code will continue to work.
[/quote]

Share this post


Link to post
Share on other sites

×

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.