In this tutorial we will learn how to create a textfile in PHP. I am going to provide you the code and explain what's going on here:
<?php $fp = fopen("carrots.txt", 'w') or die("Something went wrong, could not create file"); $text = "I am eating carrots"; fwrite($fp, $text) or die("Something went wrong, could not write to file"); fclose($fp); echo "File 'carrot.txt' was written"; ?>
If you open up your browser and run this code, you should see the text "File 'Carrots' was written". And if you look in the same folder where you saved this code you should see a new file with the name 'carrots.txt'. Let's break down this sorcery line by line. We begin with the second line as I assume that you're familiar with the opening tag in line 1:
$fp = fopen("carrots.txt", 'w') or die("Something went wrong, could not create file");
First, a variable is declared with the identifier fp, which is an abbreviation for file pointer. This variable is holding information about the file we want to open. We tell the computer to open up 'carrots.txt' and that we want to write to it with the function fopen(). This function expects you to feed it with two parameters, the name of the file you want to manipulate and how you want to manipulate the file. In this case we want to write to a file, so we put w for write to the second parameter.
If there exists a file with the name we chose, it's going to be overwritten. If not, a new file will be created. The fopen() function returns true if it's working, and false if the file couldn't be created. In this example I put the function die() to exit the program if the function would reject our wish to create a file. This is not what you want your production file to look like, I just put it there for demonstration.
In the next line we declare a string with the text we want to write to the file. And in the line after that, we make it happen:
fwrite($fp, $text) or die("Something went wrong, could not write to file");
The function fwrite() takes two parameters as well. First we pass the file pointer variable to let it know what file we want to write to, then we pass the text we want to write. Again, the function returns true on success and false on failure.
Although the program closes the file when it's finished, it's a good practice to call fclose($fp) when you're done with your file. And that would be all! Simple, right?
Enjoyed this article? Give the teacher an apple.
Articles with similar tags