user13941931
user13941931

Reputation:

How do I create and save to a text file using PHP?

I've been working on a quiz, and I've come across the need to save my answers to a text file. I've come up with some code:

<?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);
?>

But I've noticed that this only wants to write to a file with content that is already there, and it fails to create a new file and write to it. Is there any way this is possible?

Upvotes: 0

Views: 58

Answers (1)

Chilarai
Chilarai

Reputation: 1888

It should be w+ instead of r+

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

Upvotes: 1

Related Questions