每天自动显示换行形式的文本文件

时间:2019-05-28 07:31:08

标签: php

我有一个文本文件,我想每天从中读取新行 如何每天自动更新开始和结束值?

$start = 1; // array indexes are starting with zero
$end = 4;   // array indexes are starting with zero

$lines = file('test.txt'); // get lines of file as an array
for($i = $start; $i <= $end && $i < count($lines); $i++) {
    echo $lines[$i];
}

1 个答案:

答案 0 :(得分:1)

由于您已经必须让每个访问者都读取文件才能显示文本的第一行,因此可以根据需要编写一些代码来修改文件。

假设您有此文件:

2019-05-12
This is line 1
This is line 2
This is line 3

然后为每位访客提供此作品:

$text = file('myfile.txt');      // read file into array
$date = $text[0];                // get the last update date
$now = date('Y-m-d',time());     // today
$show = 1;                       // 1 = first text line in array

//if we need to update
if( $date !== $now ){
     $show = 2;                  // 2 = we need a new line
     $text[0] = $now;            // set last update to today
     unset($text[1]);            // delete the old line
     // write back file without the deleted line
     file_put_contents('myfile.txt', implode("\n",$text); 
}

echo $text[$show];

未经测试的代码,但您知道了