You may have a file hosted on your server that you want to read information from, in this quick PHP tutorial, I’ll show you an easy to understand way to do so.
Firstly, have a file, for instance, data.txt, with some sample data in it, uploaded to the server.
Some quick sample data:
hello@example.com
john@example.com
david@example.com
php@example.com
Before you can read data in from the file, you will need to open the file using fopen()
<?php $file = “data.txt”; $fp = fopen($file, “r”); fclose($fp); ?>
When done, you also need to close the file, with fclose().
Next, we want to actually read the data in, in order to do this we’ll use the fgets() function. It takes 2 variables, the first, the pointer to our open file ($fp) and the second the amount of bytes we want to read in. Every character will be a byte. However one more thing to note, fgets only goes to the end of the first line. We will also implement a while loop to make it go to the end of the file – with the help of the File End of File function.
<?php
$file = “data.txt”;
$fp = fopen($file, “r”);
while (!feof($fp)) {
$data = fgets($fp, 1024);
}
fclose($fp);
?>
Almost there, we just need to make it echo out our text:
<?php
$file = “data.txt”;
$fp = fopen($file, “r”);
while (!feof($fp)) {
$data = fgets($fp, 1024);
echo “$data<br>”;
}
fclose($fp);
?>
We add the HTML <br> tag, so that a new line begins where it is supposed to.
There is another way to do it, using a function called file() and a foreach loop.
First, we’ll set the variable $data to file(“data.txt”)
<?php $data = file(“data.txt”); ?>
Now the forwhile loop which will go through our $data array and list each one.
<?php
$data = file(“data.txt”);
foreach ($data as $value)
{
echo “$value<br>”
}
?>
Its that simple! The second one is a lot easier to work with in my opinion.
I hope my tutorial has helped and if it has don’t forget to +rep me :D ;)


Sign In
Create Account


Back to top










