【问题标题】:PHP - write to file at end of each linePHP - 在每行末尾写入文件
【发布时间】:2014-02-04 11:01:41
【问题描述】:

假设我已经有一个如下所示的文本文件:

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

【问题讨论】:

  • 读取文件,附加字符串,然后写入文件。
  • 如果每一行都是相同的字符串,你可以使用 str_replace()

标签: php file append fwrite


【解决方案1】:

这样做:

<?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));
?>

【讨论】:

    【解决方案2】:
    $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);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-10-26
      • 2018-10-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-14
      • 1970-01-01
      • 2018-08-23
      相关资源
      最近更新 更多