2011-02-24 24 views
1

我有一個文本文件,更多的是一個程序的用戶文件。我試圖使用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

只是一個說明,你可以使用file()而不是while(!feof()...)來讀取整個文件到一個數組 – 2011-02-24 15:56:27

回答

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 
} 

這樣,您將寫入新的數據,然後先對原始數據。

+0

非常感謝,這沒有訣竅:) – Kelso 2011-02-24 15:55:20

相關問題