代码仅保存循环的最后一个条目


Code is only saving the last entry of the loop

我想通过将结果写入另一个文本文件来过滤一个文本文件。

我有一点代码,它不能像它应该工作的那样工作,它只是将第一个文本文件的最后一行写入单独的备份文本文件。

法典:

//filter the ingame bans
$search = "permanently"; 
$logfile = "ban_list.txt";
$timestamp = time();
// Read from file 
$file = fopen($logfile, "r");
while( ($line =  fgets($file) )!= false)
{
    if(stristr($line,$search))
    {
        $cache_ig = "ingamebanlist.txt";
        $fh = fopen($cache_ig, 'w') or die("can't open file");
        $content = "'n";
        fwrite($fh, $content);
        $content = $line;
        fwrite($fh, $content);
        fclose($fh);    
    }
}

我个人在我的代码中没有看到任何错误,请帮助。

请记住:它确实有点工作,但它只将ban_list.txt文件的最后一行写入ingamebanlist.txt文件......

你的代码发生的情况是,你打开(使用写入模式),在循环内写入和关闭,所以它只会写入 1 个条目,然后覆盖它直到最后一个条目,从而只保存最后一项。

你想要的是像这样把它放在循环之外:

<?php
$search = "permanently"; 
$logfile = "ban_list.txt";
$cache_ig = "ingamebanlist.txt";
$timestamp = time();
$read = fopen($logfile, "r") or die("can't read file");
$write = fopen($cache_ig, 'w') or die("can't write to file");
while(($line = fgets($read)) !== false)
{
    if(stristr($line,$search))
    {
        fwrite($write, $line . "'n");
    }
}
fclose($write);
fclose($read);

另一种解决方案是使用a而不是w fopen,因为w会:

打开仅供写入;将文件指针放在文件的开头,并将文件截断为零长度。如果该文件不存在,请尝试创建它。

虽然a将:

打开仅供写入;将文件指针放在文件的末尾。如果该文件不存在,请尝试创建它。

这将允许您的代码按原样工作,除了以下行之外没有任何更改:

$fh = fopen($cache_ig, 'w') or die("can't open file");

自:

$fh = fopen($cache_ig, 'a') or die("can't open file");