PHP Randomly Reading the Content of a Specific Line in a TXT File

12,577 6

Recently, I have been developing a one-sentence output platform similar to “Yiyan.” In terms of data storage, I did not use MySQL or SQLite because I plan to store the data in txt-format text files.

The reason is simple: txt files have relatively fast read and write speeds and do not waste too much memory. This technology is also not very difficult, as it only involves using PHP to read text content. Below, I will share some of my experience.

Two Approaches

The following two approaches are introduced. The first is based on one I found online, while the second is one I came up with myself. I feel that my approach is somewhat better.

Source Code Retrieval Version

The code is as follows:

PHP
<?php
$data = file_get_contents($filename); 
//按行分割数据
$arr = explode("\n", $data);
//随机读取100行
$rand = array_rand($arr,1); print_r($rand);
?>

I will not provide too much explanation. Anyone with a basic understanding of PHP will understand it at a glance.

Array Writing Version

The basic idea is as follows: obtain the total number of lines, generate a random number, obtain the random line, and output it. The code is as follows:

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

The principle is all explained in the comments above. It should be easy enough to understand. Anyway, I think it is quite simple.

Comments

(6)
  1. Chrome 79 Windows 10

    学到了,谢谢大佬。 但是第二种方法存在一个问题,有可能取到空行(即使txt里没有空行)

  2. 沉醉于风
    Chrome 79 Windows 10

    感谢!正有需要的!

  3. 沉醉于风
    Chrome 79 Windows 10

    另外博主大大能写个PHP咋个实现根据某个字符串查找其在txt文件的哪一行并且可以对哪一行整行数据重新写入,其他行的数据不变

  4. 北云尘
    Chrome 78 Windows 10

    产生随机行号时,不应该是0到n,应该是0到n-1

  5. porry
    Chrome 86 Windows 10

    $n需要-1把 数组是按0开始计算的

Leave a comment

© 2026 Carefree. All rights reserved.

Carefree is a personal site about technology and everyday life, documenting web development, backend, and DevOps practices, plus software tools, digital experiences, and thoughts beyond code.