phpfiletextfile-manipulation

Replace specific line in text file using php while preserving to rest of the file


I have the following text file and php code, the text file holds a few minor variables and I would like to be able to update specific variables from a form.

The problem is that when the code is executed on submission it adds extra lines to the text file that prevent the variables from being read correctly from the text document. I have add the text file, code and outcomes below.

Text file:

Title
Headline
Subheadline
extra 1
extra 2

php code:

<?php
session_start();
// Get text file contents as array of lines
$filepath = '../path/file.txt';
$txt = file($filepath); 
// Check post
if (isset($_POST["input"]) && 
    isset($_POST["hidden"])) {
    // Line to edit is hidden input
    $line = $_POST['hidden'];
    $update = $_POST['input'];
    // Make the change to line in array
    $txt[$line] = $update; 
    // Put the lines back together, and write back into text file
    file_put_contents($filepath, implode("\n", $txt));
    //success code
    echo 'success';
} else {
    echo 'error';
}
?>

Text file after edit:

Title edited
Headline

Subheadline

extra 1

extra 2

Desired outcome:

Title edited
Headline
Subheadline
extra 1
extra 2

Solution

  • There are two solutions thanks to Cheery and Dagon.

    Solution one

    <?php
    session_start();
    // Get text file contents as array of lines
    $filepath = '../path/file.txt';
    $txt = file($filepath); 
    //check post
    if (isset($_POST["input"]) && 
        isset($_POST["hidden"])) {
        $line = $_POST['hidden'];
        $update = $_POST['input'] . "\n";
        // Make the change to line in array
        $txt[$line] = $update; 
        // Put the lines back together, and write back into txt file
        file_put_contents($filepath, implode("", $txt));
        //success code
        echo 'success';
    } else {
        echo 'error';
    }
    ?>
    

    Solution two

    <?php
    session_start();
    // Get text file contents as array of lines
    $filepath = '../path/file.txt';
    $txt = file($filepath); 
    // Get file contents as string
    $content = file_get_contents($filepath);
    //check post
    if (isset($_POST["input"]) && 
        isset($_POST["hidden"])) {
        $line = $_POST['hidden'];
        $update = $_POST['input'] . "\n";
        // Replace initial string (from $txt array) with $update in $content
        $newcontent = str_replace($txt[$line], $update, $content);
        file_put_contents($filepath, $newcontent);
        //success code
        echo 'success';
    } else {
        echo 'error';
    }
    ?>