Flat File Database Demo

How to read from a flat file database using PHP.

12th October 2004 · Last updated: 5th October 2016


  1. Introduction
  2. The Demo
  3. The Database
  4. The PHP Code
  5. Summary
  6. Further Reading


I received a query asking how to use PHP to read from a flat file database and output it as HTML. A 'flat file' is just another name for a plain text file. I was only too happy to help out, having used this technique over and over both at home and at work. The reason was that at work, we weren't allowed to use MySQL, the standard tool for web-based databases. I never learnt how to use it, instead learning enough basic PHP to code my own database from scratch. Everything I still do now runs off flat files. They are easy to manage because you can read them in any standard text editor, the files can be quite small and backing them up isn't a problem. Of course flat files won't match the built-in flexibility of something like MySQL, but you are free to program with them in any way you see fit. The only limit is your imagination and your coding skills.

Here is a basic demo showing a simple way to display the contents of a flat file database. You'll need a server running PHP. The demo only needs two files, plus there's nothing to set up on the server, unlike MySQL. The main file is a mix of PHP and HTML and should be saved with the extension ".php" so it will be parsed. The other file is your database. This is just a plain text file.

Next you can see the demo in action. I'll then list the exact code used and show you how it works. Feel free to copy the code and use it in your own projects.


The Database

Firstly, I've saved the following data in a text file and saved it as flat-file-data.txt. This will be called by the PHP script and put into HTML tags.

  1. row 1 cell 1|row 1 cell 2|row 1 cell 3|row 1 cell 4|row 1 cell 5|row 1 cell 6
  2. row 2 cell 1|row 2 cell 2|row 2 cell 3|row 2 cell 4|row 2 cell 5|row 2 cell 6
  3. row 3 cell 1|row 3 cell 2|row 3 cell 3|row 3 cell 4|row 3 cell 5|row 3 cell 6
  4. row 4 cell 1|row 4 cell 2|row 4 cell 3|row 4 cell 4|row 4 cell 5|row 4 cell 6
  5. row 5 cell 1|row 5 cell 2|row 5 cell 3|row 5 cell 4|row 5 cell 5|row 5 cell 6

What you see there is the raw contents of a typical flat file database. Each field is separated by a special character. In this case I'm using the pipe ("|") as it's rarely used in text. This character is known as a 'delimiter'. Whichever character you choose as a delimiter, you must make sure it will never appear in your text fields, otherwise the text will get cut off. If you need to use a character you've defined as a delimiter later on, then you can process the text before storing it in the database first, changing the delimiter to something harmless instead. Then just convert it back when reading from the database. But that's moving into advanced territory, so back to the simple stuff!

The database I've used simply shows the row and cell numbers in a table. We want to match these to a real table in HTML later, so we can be sure the script has worked properly. Any text you like can go inbetween each pipe symbol, so long as there are no linebreaks until the last field has been typed in. Each line in the database must go from left to right, no matter how long it gets, or the script won't work. (It may appear to flow over several lines in your text editor, if it has been set to wrap long lines.)

Now here is the PHP code used. It lives inside the HTML used to make up the web page. (PHP code can go anywhere you like in the HTML and is acted on first by the server, before the end result is passed to the browser. Just remember to open and close it with PHP tags, as below.)

The PHP Code

UPDATE 21st May 2010: the code below is subject to possible updates over time so check the actual demo itself for the latest code.

  1. <?php
  2. $fp = fopen('flat-file-data.txt','r');
  3. if (!$fp) {echo 'ERROR: Unable to open file.</table></body></html>'; exit;}
  4. $loop = 0;
  5. while (!feof($fp)) {
  6. $loop++;
  7. $line = fgets($fp, 1024); //use 2048 if very long lines
  8. $field[$loop] = explode ('|', $line);
  9. echo '
  10. <tr>
  11. <td>'.$field[$loop][0].'</td>
  12. <td>'.$field[$loop][1].'</td>
  13. <td>'.$field[$loop][2].'</td>
  14. <td>'.$field[$loop][3].'</td>
  15. <td>'.$field[$loop][4].'</td>
  16. <td>'.$field[$loop][5].'</td>
  17. </tr>';
  18. $fp++;
  19. }
  20. fclose($fp);
  21. ?>

I will next explain each line in detail:

  1. Line 1 is the opening PHP tag. This tells the server to send everything after it (up to the closing PHP tag) to the PHP parser, which sits on the server. The parser processes all the programming instructions you have put in. The good thing about this is that the end user never sees the PHP code, only the resulting HTML.
  2. The database shown earlier is opened for reading. The online PHP manual tells us on this page that 'r' means "Open for reading only; place the file pointer at the beginning of the file". There are many different settings you can use here, but we just want to read the file, not write to it.
  3. If the file cannot be found, we need to generate an error. The PHP command exit is used to stop processing any more code.
  4. A variable $loop is used for noting the database line numbers later on.
  5. Now a loop is started to read the contents of the database. It is set to loop until the end of the file is reached.
  6. The variable $loop is incremented by 1. This is similar to saying $loop = $loop + 1.
  7. A variable $line grabs a line of the database up to 1,024 characters.
  8. Six variables are chosen for each field, while the line of text is broken down by the delimiter. Because the pipe character was used, an extra slash is needed before it. Normal alphabetical characters and punctuation might not need the slash. The line is exploded into an array using the pipe symbol as the delimiter.
  9. Now each field is in a variable an array, we can output the contents to the browser. To do this, echo is used.
  10. An opening table row tag is echoed first.
  11. Note: If echo uses speech marks around the text that follows, then any speech marks within the text have to be 'escaped' by using a slash before each one. With large amounts of text, this becomes a big hassle. But using apostrophes instead removes the need for slashes. The only drawback is that variables have to be outside the echoed text. To echo them as well, a dot is used to join the text and the variables together.
  12. You can include linebreaks within the echo statement and include HTML tags as well.
  13. Here I have put each field inside a table cell tag.
  14. The number of variables array entries used matches the number of fields in your database, but you can miss out fields if you only want to read the first few.
  15. If you want to sort the fields before displaying them, then a second array can be used.
  16. The variable names can be anything you want. I try to match them to the database, so I might use $tel, $fax and $email, for instance. (This no longer applies.)
  17. A closing table row tag is echoed last.
  18. The 'file pointer' is incremented by one, so the loop will start reading from the next line of the database.
  19. This closes the loop.
  20. Now the file needs to be closed.
  21. Finally we need to come out of PHP so the server knows to stop parsing your file at this point. So this line has the closing PHP tag. You can keep going in and out of PHP many times during a web page file, but if you find yourself doing this with only a little bit of HTML inbetween each script, consider staying inside PHP and echoing the HTML instead.


What we have here is a very basic script that reads a flat file database just by using a loop, then breaking down the text into variables and spitting them out. You can build on this simple code in many ways. Your HTML table can become dynamic, so the user can sort it by clicking on each column header. Or you can implement a crude search form that works by reading through the database until it finds the text you need. Some web designers swear by flat file databases, claiming them to be way smaller than their MySQL equivalents. They are also a great way to learn PHP. I hope you will find my code useful. What can you do with it?

Further Reading

See my Flat File Database Demo 2 which shows you how to sort the data by each table column.

Comments (12)

Comments are locked on this topic. Thanks to everyone who posted a comment.

  1. Sarah:
    Wow... what a helpful and well written tutorial! Thank you so much. Your line by line explanations were enormously helpful.

    Posted on 15 October 2004 at 10:26 pm
  2. Febri:
    Excellent explanation, thank you very much... :-)

    Posted on 17 October 2004 at 11:29 pm
  3. Nick:
    That was a great tutorial. Two questions however:

    Is it possible to edit the info that I put into the flat file database via form, and is it possible to delete a line from the database?



    Posted on 18 October 2004 at 3:53 am
  4. Chris Hester:
    Yes, anything is possible when you get into writing the file, not just reading it. You can read the data, put it into an array, sort it, remove or add text, then simply write back to the file. (PHP has a great file method which allows you to set the contents of the file to zero, so you can easily overwrite it.) Or you can append new lines to the end of the existing file.

    A page with a form might be used to open the file and put the contents into a text area. Then it can write the changes back to the file. Obviously some security is needed there, like a password in the form, so no-one else can use it.

    If you are only changing one line though, I guess this method isn't as flexible as MySQL. What you can do is use a program like Access, then export the tables as delimited text. That's what I do at work. We have several pages that are generated from a couple of flat files. All I need to do to update the pages is simply export the files from Access again and upload them, replacing the ones on the server.

    Posted on 18 October 2004 at 10:18 am
  5. jun:
    uapik tenan jess makane belajar ambek paklek seng wes posting sep jos tenan ok :-D

    Posted on 18 October 2004 at 10:55 am
  6. will:
    Nicely done. This is one for the bookmarks.

    Posted on 18 October 2004 at 8:34 pm
  7. Jonavon:
    Just Looking

    Posted on 19 October 2004 at 2:53 pm
  8. doug:
    great explanation. It seems you are missing a row in your text file

    Posted on 30 October 2004 at 2:57 am
  9. James Welch:
    Im running a web design directory site using this nice bit of code - simple and very effective. No db whatsoever, just php and the code above - created over 1000 pages of web designers info.

    Check it out - http://www.webdesignlist.co.uk

    Posted on 29 November 2004 at 1:46 pm
  10. Michael:
    I have a question about this statement: If you want to sort the fields before displaying them, then a second array can be used.
    I'm not much of a programmer and I'm stumbling over the who array/sort thing. What would the field sort look like in your example?

    Thanks - this is a very helpful page.

    Posted on 30 November 2004 at 3:46 pm
  11. Chris Hester:
    Your comment inspired me to make a second demo! I've added the link above under Further Reading.


    Posted on 1 December 2004 at 8:20 pm
  12. Carl:
    Great tip! Thanks for posting it. Really easy "entry-level" php. All I have to do is pretty up the page and i'm all set. Thanks :-)

    Posted on 5 February 2005 at 10:11 pm