PHP - 在每行末尾写入文件

标签 php file append fwrite

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

样本.txt

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

如何将数组中的数据 append 到每行的末尾?

以下内容仅 append 到最后一行之后的行。

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

最佳答案

这样做:

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

关于PHP - 在每行末尾写入文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21146528/

相关文章:

file - Applescript:从文件中读取文本

c - 在 C 中处理 bmp 文件时,为什么 fopenf_s 会将文件指针初始化为 NULL?

javascript - jQuery append 在 getJSON 回调之外不起作用

python - append 到文件并使用数组时出错

python - Numpy 将矩阵 append 到张量

php - 如何在 laravel 中用 Eloquent 方式将两个不同表中的两列相乘

Windows 和 Linux 上的 C 文件锁定行为

php - 我应该定制一个照片库还是调整一个现有的?

php - 简单的 HTML DOM 空间转换类

php - PHP copy() 方法使用远程服务器图像文件的可靠性