我有一个包含20行的txt文件我想用输入中的新文本替换第4行...我已尝试this和其他一些但未解决我的问题。 PHP代码
<?php
if(isset($_POST['submit'])){
$selected_file = $_POST['files'];
$line = $_POST['to_line'];
$text = $_POST['text'];
//opn file
$file_open = fopen($selected_file,"r+") or die('Fail to open a file');
//fwrite($file_open,$text);
$file_array = file($selected_file);
$file_array[$line] = $text;
$file_array = implode($file_array);
file_put_contents($selected_file,$file_array);
?>
HTML
<form name="write" method="post" action="">
<table>
<tr><td>Select File</td><td><select name="files" style="width:183px;">
<?php
foreach ($a = scandir('.') as $file){
$extension = pathinfo($file, PATHINFO_EXTENSION);
if($extension == 'txt' || $extension == 'doc'){
echo"<option>".$file."</option>";
}}
?>
></select></td></tr>
<tr><td>Line</td><td><select name="to_line" style="width:183px">
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
<option>5</option>
<option>6</option>
<option>7</option>
</select>
</td></tr>
<tr><td>Write Text</td><td><textarea name="text" style=" height:120px" ></textarea></td></tr>
<tr><td></td><td><input type="submit" name="submit" value="Save" /></td></tr>
</table>
</form>
我想要什么 我想从下拉列表中选择一个值(行#),整行将替换为新文本。
答案 0 :(得分:0)
尝试以下解决方案也确保文件具有写入权限:
if(isset($_POST['submit'])) {
$selected_file = $_POST['files'];
$line = $_POST['to_line'];
$text = $_POST['text'];
$file_array = file($selected_file);
$file_array[$line - 1] = $text."\n";
$file_content = implode("", $file_array);
$f = fopen($selected_file, 'w+') or die('unable to open');
fwrite($f, $file_content);
fclose($f);
}