2

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
Manuel Allenspach
  • 12,467
  • 14
  • 54
  • 76
Alex
  • 6,610
  • 3
  • 20
  • 38
  • 2
    `implode("", $txt)` as every original element of `$txt` already has a new line symbol at the end. just add it too to the elements you are inserting by yourself. `$txt[$line] = $update . "\n";` or you can use `PHP_EOL` instead of `"\n"` (it depends on each specific case) – Cheery Nov 19 '14 at 23:33
  • 1
    just using str_replace would be much faster –  Nov 19 '14 at 23:47

1 Answers1

3

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';
}
?>
Alex
  • 6,610
  • 3
  • 20
  • 38