|
Posted by NC on 09/26/37 11:41
guttyguppy@gmail.com wrote:
>
> I know that file('mytext.txt'); will return an array of all the lines
> of text in mytext.txt. What I want is to grab the text from random line
> in mytext.txt.
>
> $lines = file('words.txt');
> $random = rand() % 100;
> echo "line=" . $lines[$random];
>
> The problem is I have a very long text file, and each time the php page
> is loaded there is a delay as it needs to assemble the enormous array.
>
> How can I tell the php page to locate the random line number in
> mytext.txt and only load that variable?
The fastest way I can think of is this:
1. Determine file size with filesize().
2. Select a random number between 0 and file size with rand().
3. Open the file for reading with fopen().
4. Go to the byte with the number randomly selected in Step 2
with fseek().
5. Read a line with fread(); if fread() returns FALSE, rewind()
and fread() again.
6. The line read in Step 5 is most likely incomplete, so you
need to read another line with another fread(); again, if
fread() returns FALSE, rewind() and fread() again.
The line read in Step 6 is the random line you seek...
Cheers,
NC
Navigation:
[Reply to this message]
|