我有一个文本文件,更多的是一个程序的用户文件。我试图使用 PHP 在组之前插入新数据:在文件中。最后一个用户在此行上方,我想在最后一个用户和以上组下方插入新用户:在文件中
我一直在修补并尝试一些东西,但我只能在那条线之后得到它。
这是我所拥有的
$key = 'groups:';
$newline = 'blackberry';
//copy file to prevent double entry
$file = "data2.yml";
$newfile = "filetemp.txt";
copy($file, $newfile) or exit("failed to copy $file");
//load file into $lines array
$fc = fopen ($file, "r");
while (!feof ($fc))
{
$buffer = fgets($fc, 4096);
$lines[] = $buffer;
}
fclose ($fc);
//open same file and use "w" to clear file
$f=fopen($newfile,"w") or die("couldn't open $file");
/* uncomment to debug */
print_r($lines);
print "
\n";
//loop through array using foreach
foreach($lines as $line)
{
fwrite($f,$line); //place $line back in file
if (strstr($line,$key)){ //look for $key in each line
fwrite($f,$newline."\n");
} //place $line back in file
}
fclose($f);
copy($newfile, $file) or exit("failed to copy $newfile");
?>
它是一个 yml 文件,所以我不能在之后添加额外的行,否则它会搞砸并拒绝运行。
谢谢!