PHP Randomly Reading the Content of a Specific Line in a TXT File
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
$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
$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)学到了,谢谢大佬。 但是第二种方法存在一个问题,有可能取到空行(即使txt里没有空行)
在什么情况下会获取到空行,能否提供一下txt
感谢!正有需要的!
另外博主大大能写个PHP咋个实现根据某个字符串查找其在txt文件的哪一行并且可以对哪一行整行数据重新写入,其他行的数据不变
产生随机行号时,不应该是0到n,应该是0到n-1
$n需要-1把 数组是按0开始计算的