2

Assume I already have a text file which looks like:

sample.txt

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

How can I append data from an array to the END of each line?

The following ONLY attaches to the line following the last line.

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
}

Desired Result:

    This is line 1.append_1
    This is line 2.append_2
    This is line 3.append_3
    .
    .
    .
    This is line n.append_n
2
  • 3
    Read the file, append the strings and then write to file. Commented Jan 15, 2014 at 19:33
  • if it was the same string for every line you could use str_replace() Commented Jan 15, 2014 at 19:37

2 Answers 2

3

Do this :

<?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));
?>
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.