2013-11-21 21 views
1

想象我有以下內容的TXT文件:PHP寫在特定的位置

Hello 
How are you 
Paris 
London 

我想寫巴黎之下,所以巴黎的2索引,我想寫的3.

目前,我有這樣的:

$fileName = 'file.txt'; 
$lineNumber = 3; 
$changeTo = "the changed line\n"; 

$contents = file($fileName); 
$contents[$lineNumber] = $changeTo; 

file_put_contents($fileName, implode('',$contents)); 

但它只改變特定行。我不想修改,我想寫一個新的行,讓其他人留在原地。

我該怎麼做?

編輯:已解決。在一個非常簡單的方法:

$contents = file($filename);  
$contents[2] = $contents[2] . "\n"; // Gives a new line 
file_put_contents($filename, implode('',$contents)); 

$contents = file($filename); 
$contents[3] = "Nooooooo!\n"; 
file_put_contents($filename, implode('',$contents)); 
+0

使用[array_splice()](http://www.php.net/function.array-splice)注入新的條目到$內容陣列 –

+0

請訪問http://計算器。 com/questions/3797239/insert-new-item-in-array-on-any-position-in-php – jszobody

+0

http://stackoverflow.com/questions/2149233/how-to-add-an-array-value-我認爲@jszobody – m59

回答

2

你需要一個新的數組來解析該文件中的內容,將內容,並在您需要的行號出現,將新的內容放到這個數組。然後將新內容保存到文件中。下面的代碼調整:

$fileName = 'file.txt'; 
$lineNumber = 3; 
$changeTo = "the changed line\n"; 

$contents = file($fileName); 

$new_contents = array(); 
foreach ($contents as $key => $value) { 
    $new_contents[] = $value; 
    if ($key == $lineNumber) { 
    $new_contents[] = $changeTo; 
    } 
} 

file_put_contents($fileName, implode('',$new_contents)); 
+0

感謝您的幫助。 – user2902515