This article describes how to randomly retrieve a data instance in the php file. I hope this tutorial will be helpful to you.
| The Code is as follows: |
Copy code |
<? Php
// Method 1:
$ Line = getrandline1('test.txt ');
Function getrandline1 ($ filename)
{
$ Linenum = 0;
$ Fh = fopen ($ filename, 'R ');
While (! Feof ($ fh ))
{
If ($ rowcontents = fgets ($ fh ))
{
$ Linenum ++;
$ Contens [] = $ rowcontents;
}
}
$ Randline = mt_rand (0, $ linenum-1 );
$ Line = $ contens [$ randline];
Fclose ($ fh );
Return $ line;
}
// Method 2:
$ Line = getrandline2('test.txt ');
Function getrandline2 ($ filename)
{
$ Contents = file('test.txt ');
$ Linenum = count ($ contents );
$ Randline = mt_rand (0, $ linenum-1 );
$ Line = $ contents [$ randline];
Return $ line;
}
// Method 3:
$ Line = getrandline3('test.txt ');
Function getrandline3 ($ filename)
{
$ Contents = file('test.txt ');
Shuffle ($ contents );
Return $ contents [0];
}
// Method 4:
$ Line = getrandline4('test.txt ');
Function getrandline4 ($ filename)
{
$ Linenum = 0;
$ Fh = fopen ($ filename, 'R ');
While (! Feof ($ fh ))
{
If ($ linecontents = fgets ($ fh ))
{
$ Linenum ++;
$ Randint = (mt_rand (1, 1000000 * $ linenum)-1)/1000000 );
If ($ randint <1)
{
$ Line = $ linecontents;
}
}
}
Fclose ($ fh );
Return $ line;
}
?> |