在我阅读了很多关于文件的编辑/更新功能的类似问题并且没有一个起作用之后,我想寻求一些帮助。
我正在尝试从 php 编辑一个 .txt
文档。我试过这些东西:
这是我在这里读到的最后一个代码,但没有用。
$data_to_write = "$_POST[subject]"; $file_path = "text/" + $row['name']; $file_handle = fopen($file_path, 'w'); fwrite($file_handle, $data_to_write); fclose($file_handle);
这是我之前的尝试:
$new_contents = "$_POST[subject]\n"; $path = "text/$row[name]"; file_put_contents($path, $new_contents);
我希望有人能向我解释如何以正确的方式做到这一点。谢谢。
这是我的全部代码:
<?php
if(isset($_GET['id']))
{
$edit = mysql_query("SELECT * FROM text_area WHERE text_id=$_GET[id]");
$row = mysql_fetch_assoc($edit);
$contents = file_get_contents($row['content']);
?>
<form action="" name="form" method="post">
<input type="hidden" name="id" value="<?php echo $row['text_id']; ?>" /><br />
<label for="">Заглавие:</label><br />
<input type="text" name="title" style="width:500px;" value="<?php echo $row['subject'] ?>" /><br />
<select name="opt">
<option value="0"></option>
<?php
$result = mysql_query("SELECT * FROM image_area");
while ($row = mysql_fetch_array($result))
{
echo "<option value=" . $row['path'] . ">" . $row['name'] . "</option>
";
}
?>
</select><input type="button" name="sumbitP" value="Choose" onclick="addtext();" /><a href="../image_list.php" target="_blank">Image list</a><br />
<textarea rows="10" cols="50" name="text" id="markItUp"><?php echo $contents ?></textarea><br />
<input type="submit" name="sumbitT" value="Update" />
<input type="reset" value="Reset" />
</form>
<?php
}
?>
<?php
if(isset($_POST['id']))
{
if(mysql_query("UPDATE text_area SET title='$_POST[subject]' WHERE text_id ='$_POST[id]'"))
{
$data_to_write = "" . $_POST['text'];
$file_path = "text/$row[name]";
$file_handle = fopen($file_path, 'w');
fwrite($file_handle, $data_to_write);
fclose($file_handle);
echo '<br><br><p align="center">Everything is ok</p>';
} else {
echo '<br><br><p align="center">Everything is not ok</p>' ;
}
?>
只是添加一些可能有用的东西:
我收到这个错误,我无法通过 Google 找到答案。
警告:fopen(text/) [function.fopen]:无法打开流:是一个目录
最佳答案
你只需要改变:
$file_path = "text/" + $row['name'];
为此:
$file_path = "text/" . $row['name'];
PHP 中的连接运算符是.
(不是+
)
并确保目录 text
存在,否则最好检查然后写入:
$data_to_write = $_POST['subject'];
$file_path = "text/" . $row['name'];
if ( !file_exists("text") )
mkdir("text");
$file_handle = fopen($file_path, 'w');
fwrite($file_handle, $data_to_write);
fclose($file_handle);
关于php - 如何使用 php 编辑/更新 txt 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18865548/