我有一个文本文件,更多是程序的用户文件。我试图使用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文件,所以我不能添加额外的行后发布或它搞砸了并拒绝运行。
谢谢!
答案 0 :(得分:3)
你的foreach代码应该是:
foreach($lines as $line)
{
if (strstr($line,$key)){ //look for $key in each line
fwrite($f,$newline."\n"); //insert data before line with key
}
fwrite($f,$line); //place $line back in file
}
这样,您将先写入新数据,然后再写入原始数据。