【问题标题】:Can't use anything with "+" when using fopen in PHP [duplicate]在 PHP 中使用 fopen 时不能使用任何带有“+”的东西 [重复]
【发布时间】:2017-05-17 04:37:27
【问题描述】:

我想在PHP 中读写.txt 文件,我已经可以使用读取文件了

$Readfile = fopen("file.txt", "r") or exit("Unable to open file!");

由于我想覆盖文件,所以我建议使用

$Readfile = fopen("file.txt", "r+") or exit("Unable to open file!");

但总是得到“无法打开文件!”我也尝试过使用w+ 之类的其他方法,但仍然没有给出任何结果。这里是我的代码的一些更新

<?php
        //$Readfile = fopen("pengumuman.txt","r") or exit("Unable to open file!");
        $Readfile = file_get_contents("pengumuman.txt");
        if (isset($_POST["btnSimpan"])) {
            $pengumuman = $_POST["pengumuman"];
            fwrite($Readfile, $pengumuman);
        }
?>

<textarea class="span12" style="min-height: 200px; height: auto;" name="pengumuman">
<?php
     while(!feof($Readfile)) {
     echo fgets( $Readfile);
     }
?>

我试过file_get_contents,但它给了我一个很长的加载和空白文本区域

【问题讨论】:

    标签: php fopen


    【解决方案1】:

    代码没有问题,因为我在 linux 中运行它,所以我需要更改权限。处理完之后,一切都按应有的方式运行。谢谢你。如果您遇到这种情况,请点击此链接php can't write to file in linux

    【讨论】:

      【解决方案2】:

      不使用它,你可以试试:

      $Readfile = file_get_contents("file.txt");
      

      PHP 可以更好地处理该过程。之后,如果你想写入文件,你可以这样使用file_put_contents

      if (file_put_contents("file.txt", $Readfile . "Additional Content Here"))
        echo "File written!";
      else
        echo "Error writing file!";
      

      【讨论】:

      • 我也可以直接保存到.txt文件吗?
      • @AndreasChandraGaozu 是的,我也给出了编写文件的说明。检查更新的答案?
      • @AndreasChandraGaozu 能不能简单地说一下,你想做什么?
      • 我想读取文件,然后通过 PHP 更新文件内容,我可以从 $Readfile = file_get_contents("file.txt");它给了我很长的加载时间并且不显示文件的结果
      • @AndreasChandraGaozu file.txt 有多大?
      猜你喜欢
      • 1970-01-01
      • 2021-10-09
      • 1970-01-01
      • 1970-01-01
      • 2017-06-26
      • 1970-01-01
      • 1970-01-01
      • 2019-03-04
      • 1970-01-01
      相关资源
      最近更新 更多