プログラム用のユーザー ファイルに近いテキスト ファイルがあります。PHP を使用して、ファイル内の groups: の前に新しいデータを挿入しようとしています。最後のユーザーはこの行の上にあり、最後のユーザーの下とグループの上に新しいユーザーを挿入したい: ファイル内
私はいじくり回していくつかのことを試していましたが、その行の後にしか取得できません。
これが私が持っているものです
$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 ファイルなので、後で投稿するために余分な行を追加することはできません。そうしないと、失敗して実行を拒否します。
ありがとう!