How to create a textfile and write to it
TAGS: PHP, fopen, fwrite


Often you may need to write a file on your server. Maybe for some configuration, or maybe just to hold some information till later. Or simply your users need to create stuff, where a basic flat textfile does the job and does it good, small size, simplicity etc.

To write a textfile is very simple. Below here I give you a working example. Put the code in a file, name it 'writetext.php' and call it from you server. If the textfile does not exists the code will create it.

<?php 
$String = "Hello World!\n\nThis is a test in creating a textfile, and writing to it."; 

$mytextfile = fopen("file.txt", "a") or die("An error occurred. <A HREF='formmail.php'>Send webmaster a message</A>"); 

fwrite($mytextfile, $String); 
fclose($mytextfile); 

echo 'Super, you have created a file'; 

?>


fopen have following options;

'r' (read only, file pointer at the beginning) 
'r+' (read and write, file pointer at the beginning) 
'w' (write only, file pointer at the beginning, zero length file, create it if it does not exist) 
'w+' (read and write, file pointer at the beginning, zero length file, 
create it if it does not exist) 
'a' (write only, file pointer at the end, zero length file) 
'a+' (read and write, file pointer at the end, zero length file) 
'x' (write only, file pointer at the beginning, if exists, return FALSE) 
'x+' (read and write, file pointer at the beginning, if exists, return FALSE)


You can put all kinds of things in a textfile. At a later post I will create an XML file, we will both write it, and read it. But we will use only this example (writing) for that. PHP have a module for handling XML, we will use that for reading the content.

Look out for that post, sign up for email notification when new things happens here on this blog.

Next: How to read from a textfile