Using Flat Files (Reading)

A short tutorial on how to store information in text files and then read from the file and display the results on page.

In category php.

Posted by Joseph Skidmore on 12.09.05.

Now we have written to our text file it is time to read from it and display the data on the page.

The easiest way to retrieve the data from our text file would be to use the following code;

<?php
	readfile("data.txt");
?>

In doing so it would display all data from inside the text file on one line. Not very neat I'm sure you will agree.

Let's change the way our data will be displayed on the page. To do this we will put the output in a loop and put each record on a line of it's own.

<?php

$array = file("data.txt");

foreach($array as $row) {

echo "Name: {$row}
"; } ?>

Which would output:

name1
name2
name3
name4
etc

Using flat files is a very simple way of storing data if you don't have access to any form of database (MySQL for example), the problem with flat files being you are unable to manipulate data in the way in which you could if it was stored inside a database.

Page generated in 0.0013 seconds.

Whatcounter Free Invisible Stats CounterFree invisible hit counter