Php 文本抓取和回显?
我正在努力做到这一点,每周我的php代码都会将文本存储在一个预先制作好的文本文件中,echo每周都会输出一行新的内容。我试过使用Php 文本抓取和回显?,php,html,Php,Html,我正在努力做到这一点,每周我的php代码都会将文本存储在一个预先制作好的文本文件中,echo每周都会输出一行新的内容。我试过使用date(),但结果并没有达到我的预期 代码如下: <?php error_reporting(-1); ini_set('display_errors', 'On'); $text = file_get_contents("lines.txt"); $text = trim($text); //This removes bl
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>";
?>
如果只需要回显文本文件中的行:
$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>';
您至少需要在某个地方保留一个标志来指示一周。所以我的问题是每个测试文件有多少周?如果它有3行,就像你写的那样,一个人如何在没有标记的情况下跟踪一周的下一行。使用日期时发生了什么?你可以在该行日期上添加偏移或注释。