Working with Files in PHP (The Brief Way)

Discover the efficient and concise way of working with files in PHP with this guide. Learn how to read, write, and manipulate files using built-in PHP functions and practical examples. Improve your file handling skills and optimize your PHP code for better performance and reliability.

Files are essential to large scale web applications. Wherever we have some kind of resource management and planning, the idea to log changes and variations or create reports it’s crucial for providing optimal insight to sales, accounting and managing departments. Even from the developers’ perspective, being able to generate CSV or JSON files on demand for various purposes, will speed up development and boost productivity, leading to more features for other departments to leverage.

PHP offers an very robust way to generate and manipulate files. Assuming some basic understanding in the language itself, you’re going to need to implement the behavior and test it out on your machine. Feel free to use the snippets below to avoid unnecessary hold ups and potential errors. I suggest you to skip the copy-paste part and hard code everything yourself for maximum retention (you may follow the video provided as well). That’s the way you learn new concepts in programming. You expose yourself to them!

The first order of business it’s to learn how to read something from a file before editing and writing into it. The most common action when dealing with files is to read it, not write it. The reason is simple. We usually need to parse the data for a specific goal and we don’t care what happens to the file after we access it. In case we need to update it later on, that’s a different story.

Reading a Text File

To successfully read a file in PHP you’re going to need two things, the filename and the file pointer that points to that particular file. So, let’s create a file in Visual Studio Code or editor of choice and put some lines to it and use fopen() and the mode to open the file stats text file.

$file_name = 'stats.txt';
$f = fopen($file_name, 'r');

This is a test line text. This is a hello world
Another test world. This is the end of the line
This is how you do it. The final line of the file

Print the Contents of the File

The next step is to use the file pointer from the previous section to successfully print the contents of the file in a line fashion. Printing, in some cases it’s equivalent to parsing since usually, we have to do some kind of operation to each line once we read it. In this case we will use the explode function to separate the line to the separator of choice and obtain an array. The separator, if we take in account the format of the text file, will be set to the full stop (dot).

$file_name = 'stats.txt';
$f = fopen($file_name, 'r');

/* create an array to store the parsed lines */
$lines = array();

/* while not the end of file */
while (!feof($f)){
   /* get the line using fgets() */
   $line = fgets($f);
   /* split the line using the dot and store it */
   $lines[] = explode('.', $line);

The idea you need to follow can be dissected into three steps. One: Create the array that’s going to hold the parsed data. Two: Decide how you want to parse the data once it’s available. Three: Once you have the data, you can either use a persistence technique to store it or put it on a new file, should the case allows it.

Write to the File

Now that you’ve seen how to read and extract data from a text file, the next logical step that we need to consider is how to edit and make modifications to it. In the previous section, we posited that if such case arises that we need to store something to a file, we should do so. But how can you do it? It’s all fine and dundy until the moment we’re tasked to implement something. So, in order to write to that particular file, we need two things. One: To change the mode that we open the file and two, use the fwrite function by passing the file pointer and the content of our choice.

$file_name = 'stats.txt';
$f = fopen($file_name, 'a');
fwrite($f, 'This is a test line');

If you want to follow along in your own pace, or if you didn’t quite conquer the concept yet, I encourage you to watch the video below which contains detailed instructions and a hands on example so you can fully grasp what’s going on.