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.