I just started programming on php. I need my script to open or create (fopen())
a plain text file at the end of the script. I am using Ubuntu.
The book I am following suggests,
@ $fp = fopen(“$DOCUMENT_ROOT/../orders/orders.txt”, 'ab');
but I am programming on my local machine, so I tried the script to create “orders.txt” on an alternative path:
'/opt/lampp/htdocs/orders/orders.txt'
This doesn't seem to work, although some time ago I think I was able to make it work on Windows,
I am only some weeks into this,
Thank you,
S.
Refer fopen manual:-
Try this code:-
<?php
$myfile = fopen("newfile.txt", "w") or die("Unable to open file!");
$txt = "John Doe
";
fwrite($myfile, $txt);
$txt = "Jane Doe
";
fwrite($myfile, $txt);
fclose($myfile);
?>
Rahul Dhande's answer is perfect.
Here is another alternative. You can also use
file_put_contents — Write a string to a file
file_get_contents — Reads entire file into a string
$file = 'people.txt';
// Open the file to get existing content
$current = file_get_contents($file);
// Append a new person to the file
$current .= "John Smith
";
// Write the contents back to the file
file_put_contents($file, $current);
Hope it will help you :)