2013-05-16 43 views
5

我是新來的。
無論如何,我在fwrite()上做了我的研究,但是我找不到解決方案,所以我在尋求幫助。 我想要的是f.e.在其他特定行之後添加一行新文本。 F.e.我有一個txt文件,其中有:PHP fwrite()如何在特定行後插入新行

//Users 

//Other stuff 

//Other stuff2 

現在,我想什麼做的是能夠增加用戶//下面的一個新的用戶無需觸摸「其他東西」和「其他資料2」 。因此,它應該是這個樣子:

//Users  
Aneszej 
Test321 
Test123 

//Other stuff 

//Other stuff2 

我有什麼至今:

$config = 'test.txt'; 
$file=fopen($config,"r+") or exit("Unable to open file!"); 

$date = date("F j, Y"); 
$time = date("H:i:s"); 

$username = "user"; 
$password = "pass"; 
$email = "email"; 
$newuser = $username . " " . $password . " " . $email . " " . $date . " " . $time; 

while (!feof($file)) { 
    $line=fgets($file); 
    if (strpos($line, '//Users')!==false) { 
     $newline = PHP_EOL . $newuser; 
    } 

} 

fwrite($file, $newline); 

fclose($file); 

test.txt文件

//Users 

//Something Else 

//Something Else 2 

但這個只寫用戶的結束。 txt文件。

非常感謝大家的幫助!它解決了。

+0

你可以試試fseek – Hackerman

+0

我覺得當你的文件操作開始有點複雜時,你應該使用數據庫。嘗試SQLite,應該很適合你... –

+0

這只是一個例子,我將用它來做其他事情。感謝您的信息。 – Aneszej

回答

5

我修改了你的代碼,我覺得下面是你需要的,而且我也發表評論,下面的功能會不斷添加新用戶,你可以添加檢查用戶存在的條件。

$config = 'test.txt'; 
$file=fopen($config,"r+") or exit("Unable to open file!"); 

$date = date("F j, Y"); 
$time = date("H:i:s"); 

$username = "user"; 
$password = "pass"; 
$email = "email"; 
$newuser = $username . " " . $password . " " . $email . " " . $date . " " . $time."\r\n"; // I added new line after new user 
$insertPos=0; // variable for saving //Users position 
while (!feof($file)) { 
    $line=fgets($file); 
    if (strpos($line, '//Users')!==false) { 
     $insertPos=ftell($file); // ftell will tell the position where the pointer moved, here is the new line after //Users. 
     $newline = $newuser; 
    } else { 
     $newline.=$line; // append existing data with new data of user 
    } 
} 

fseek($file,$insertPos); // move pointer to the file position where we saved above 
fwrite($file, $newline); 

fclose($file); 
+0

非常感謝,正如我想要的那樣正常工作!並感謝您評論每件事情。 – Aneszej

0

您在閱讀結束時編寫新內容,因此必須在文件末尾寫入 - 在讀取所有行後光標位於該處。

您可以將所有內容存儲在php變量中並最終覆蓋該文件,或者按照Robert Rozas評論所述,使用fseek重繞光標。這應該儘快讀完「其他」一行。

0

你找到 '//用戶' 後,您需要break。你繼續閱讀文件的末尾。