本文章來給大家介紹php 文件中隨機取出一條數據實例,希望此教程對各位同學會有所幫助哦。
代碼如下
復制代碼
<?php
//第一種方法:
$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;
}
//第二種方法:
$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;
}
//第三種方法:
$line = getrandline3('test.txt');
function getrandline3($filename)
{
$contents = file('test.txt');
shuffle($contents);
return $contents[0];
}
//第四種方法:
$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;
}
?>