2014-01-15 54 views
2

假設我已經有一個文本文件,它看起來像:PHP - 寫在每一行的末尾到文件

sample.txt的

This is line 1. 
This is line 2. 
This is line 3. 
. 
. 
. 
This is line n. 

我如何可以追加從數據數組到每行的結束?

以下僅適用於最後一行之後的行。

appendThese = {"append_1", "append_2", "append_3", ... , "append_n"}; 

foreach($appendThese as $a){ 

    file_put_contents('sample.txt', $a, FILE_APPEND); //Want to append each array item to the end of each line 
} 

所需的結果:

This is line 1.append_1 
    This is line 2.append_2 
    This is line 3.append_3 
    . 
    . 
    . 
    This is line n.append_n 
+3

讀取文件,追加字符串,然後寫入文件。 – DWolf

+0

如果它對於你可以使用的每一行都是相同的字符串str_replace() – 2014-01-15 19:37:39

回答

2

這樣做:

<?php 
$file = file_get_contents("file.txt"); 
$lines = explode("\n", $file); 
$append= array("append1","append2","append3","append4"); 
foreach ($lines as $key => &$value) { 
    $value = $value.$append[$key]; 
} 
file_put_contents("file.txt", implode("\n", $lines)); 
?> 
0
$list = preg_split('/\r\n|\r|\n/', file_get_contents ('sample.txt'); 
$contents = ''; 
foreach($list as $key => $item) 
    $contents .= "$item.$appendThese[$key]\r\n"; 
file_put_contents('sample.txt', $contents); 
相關問題