0 レビュー
1 回答
ファイルの残りの部分を保持しながら、phpを使用してテキストファイルの特定の行を置き換えます
次のテキストファイルと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
わからない
0
レビュー
答え :
解決策:
CheeryとDagonのおかげで2つの解決策があります。
ソリューション1
<?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';
}
?>
ソリューション2
<?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';
}
?>
わからない
同様の質問
私たちのウェブサイトで同様の質問で答えを見つけてください。