首页 > 解决方案 > 如何使用 PHP 创建并保存到文本文件?

问题描述

我一直在做一个测验,我发现需要将我的答案保存到一个文本文件中。我想出了一些代码:

<?php
    $myfile = fopen("myfile.txt", "r+") or die("Unable to open file!");
    $txt = "Name:\n";
    fwrite($myfile, $txt);
    $txt = "Student1\n";
    fwrite($myfile, $txt);
    $txt = "Marks:\n";
    fwrite($myfile, $txt);
    $txt = "0\n";
    fwrite($myfile, $txt);
    echo fread($myfile,filesize("myfile.txt"));
    fclose($myfile);
?>

但我注意到这只是想写入一个内容已经存在的文件,并且它无法创建一个新文件并写入它。有什么办法可以吗?

标签: phptext

解决方案


它应该w+代替r+

$myfile = fopen("myfile.txt", "w+")

推荐阅读