我正在努力使我的php代码每周都会获取已经存储在预制文本文件中的文本,并且每周都会回显出一个新行。我试过使用date()
但结果并没有达到我的预期。
这是代码:
<?php
error_reporting(-1);
ini_set('display_errors', 'On');
$text = file_get_contents("lines.txt");
$text = trim($text); //This removes blank lines so that your
//explode doesn't get any empty values at the start or the end.
$array = explode(PHP_EOL, $text);
$lineNumber = count($array);
echo "<p>{$array[0]}</p>";
?>
以下是行.txt的格式:
- 你好1
- 你好2
- 你好3
等等
如果您只需要从文本文件中回显行:
$array = explode(PHP_EOL, $text);
foreach($array as $val){
echo "$val'n";
}
如果你想每周回显一个新行,请在某处跟踪它,例如:
$counter = 0;
if(!file_exists("date.txt")){
file_put_contents("date.txt",date("d"));
}else{
$date = file_get_contents("date.txt");
$dayNow = date("d");
$counter = ($dayNow - $date)/7;
}
$text = file_get_contents("lines.txt");
$text = trim($text);
$array = explode(PHP_EOL, $text);
echo $array[$counter]."'n";
这是一个解决方案 - 如果我理解正确您的问题:
<?php
$fname = 'quoteoftheweek.txt';
if (!file_exists($fname)) {
$quote = '???'; // File does not exist
} else {
$lines = file($fname, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
$nweek = (integer)date('W',time()); // Get the week number
$nlines = count($lines); // Get the number of lines
// Calculate the index as week_number modulo number_of_lines
// If number_of_lines < 1 set it to false
$index = ($nlines>0) ? ($nweek % $nlines) - 1 : false;
$quote = ($index!==false) ? $lines[$index] : '???';
}
echo '<p>Quote, week '.$nweek.' : ' . $quote . '</p>';
本周报价.txt文件的内容:
本周报价 1
本周报价 2
本周报价 3
本周报价 4
本周报价 5
本周报价 6
.......
结果 (2016-02-15(:
报价,第 7 周:第 7 周报价
笔记:
- 该解决方案将文本文件直接读取到数组中。
换行符只需一个步骤即可删除,并跳过空行。 - 它将此数组中的索引计算为周数模数行数。因此,如果行数少于周,则重用行数。
- 如果文本文件应为空或不存在,则会显示"???"而不是引号。