2

我有以下文本文件和 php 代码,文本文件包含一些次要变量,我希望能够从表单更新特定变量。

问题是,当代码在提交时执行时,它会在文本文件中添加额外的行,从而阻止从文本文档中正确读取变量。我在下面添加了文本文件、代码和结果。

文本文件:

Title
Headline
Subheadline
extra 1
extra 2

php代码:

<?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';
}
?>

编辑后的文本文件:

Title edited
Headline

Subheadline

extra 1

extra 2

期望的结果:

Title edited
Headline
Subheadline
extra 1
extra 2
4

1 回答 1

3

感谢 Cheery 和 Dagon,有两种解决方案。

解决方案一

<?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';
}
?>

解决方案二

<?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';
}
?>
于 2014-11-20T00:21:42.880 回答