You can randomly retrieve a piece of data from the PHP file in four ways. 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 the code? First php method: $ lin this article will introduce you to randomly retrieve a data instance from the php file. I hope this tutorial will be helpful to you.
The code is as follows: |
|
// 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; } ?> |
The examples file randomly retrieves a data instance. I hope this tutorial will help you. The code is as follows? Php // Method 1: $ lin...