通过php随机读取txt文件的某一行

求完整的源文件

        PHP随机读取TXT文件的某一行,基本思路是这样的:获得总行数、产生随机数、获得随机行,例子代码如下:

<?php
  $f='1.txt';//文件名
  $a=file($f);//把文件的所有内容获取到数组里面
  $n=count($a);//获得总行数
  $rnd=rand(0,$n);//产生随机行号
  $rnd_line=$a[$rnd];//获得随机行
  echo "$rnd / $n : $rnd_line \n"; //显示结果
?>


        ä»¥ä¸Šç¨‹åºåœ¨æˆ‘的电脑上执行几次的结果如下:

E:\TEMP\文件\exp>a.php
1 / 8 : [00:05.33]你拿什么来爱我2

E:\TEMP\文件\exp>a.php
3 / 8 : acfp6o7ib----803sb7rmvz----1525175080=

E:\TEMP\文件\exp>a.php
1 / 8 : [00:05.33]你拿什么来爱我2

E:\TEMP\文件\exp>a.php
1 / 8 : [00:05.33]你拿什么来爱我2

E:\TEMP\文件\exp>a.php
5 / 8 : bxi2jw97----0vaf3bw17s----1525184793=
温馨提示:答案为网友推荐,仅供参考
第1个回答  推荐于2017-11-26
$data = file_get_contents($filename); 
//按行分割数据
$arr = explode("\n", $data);
//随机读取100行
$rand = array_rand($arr,1); print_r($rand);

追问

随机读取100行?我只要一行……

追答你被上面的注释迷惑了,$rand = array_rand($arr,1);

追问

$data = file_get_contents($filename);
$arr = explode("\n", $data);
$rand = array_rand($arr,1);
print_r($rand);
这就是全部代码呗?

追答

本回答被提问者采纳
第2个回答  2013-10-28
        $read = 10;//要读取第10行
        $handle = @fopen("D:\TT\Temp.txt", "r");
        if ($handle) {
            $i = 1;
            while (!feof($handle)) {
                if($i!=$read){
                    $i++;
                    continue;
                }
                $buffer = fgets($handle, 10240);
                $this->tempFileDeal($buffer);
                $i++;
                set_time_limit(0);
            }
            fclose($handle);
        }

第3个回答  2013-10-28
$data = file_get_contents($filename);

//按行分割数据
$arr = explode("\n", $data);
//返回第n行

return $arr[$n-1];
第4个回答  2015-10-07
$read = 10;//要读取第10行
$handle = @fopen("D:\TT\Temp.txt", "r");
if ($handle) {
$i = 1;
while (!feof($handle)) {
if($i!=$read){
$i++;
continue;
}
$buffer = fgets($handle, 10240);
$this->tempFileDeal($buffer);
$i++;
set_time_limit(0);
}
fclose($handle);
}