PHP fget: read a file line by line

To get only one line of a text file, or get line by line, we have to use fget() php function instead of fread() .

We saw in the previous lesson, that if you want to read a file, you can open it and put all it's content in some variable. But in this script we will see how to get the data from the file line by line until the end of file is reached:
<?php

$filename = 'myfile.txt' ;
$file = fopen($filename , 'r' ) or exit ( "Enable to open file");

while(!feof($file))
{
echo fgets($file) . "<br />" ;
}

?>

Why to use this script:
Let's say you have a text file with many line:

----myfile.txt------
Hello Word.
We love PHP !
Here are great tutorials
And scripts and codes !
--------------------

if you use this script
$contents = fread($handle, filesize($filename));
echo $contents;
This will show:
Hello Word.We love PHP !Here are great tutorialsAnd scripts and codes !
And this is beacuse HTML script don't understand the new line character, so you need to create a new line with "<br />".

So we have to use:

<?php

$filename = 'myfile.txt' ;
$file = fopen($filename , 'r' ) or exit ( "Enable to open file");

while(!feof($file))
{
echo fgets($file) . "<br />" ;
}

?>
Display:
Hello Word.
We love PHP !
Here are great tutorials
And scripts and codes !

5 comments:

Amine said...

Thank you;
I look for this information and in forums i fund only questions!!!
really...thanks.

Diablo 3 Items said...

Cute tale. Helps make me personally wish to be much better. Thanks for sharing. You might be fantastic.
sell d3 gold



Diablo 3 gold

Guild wars 2 gold said...

wonderful submit... will help me a good deal,it is Exactly what I was trying to find! diablo 3 gold, i like it very much.

mary Brown said...

I have read your blog its very attractive and impressive. I like it your blog.

PHP Training in Chennai | Online PHP Training

PHP Training in Chennai | Online PHP Training

caroline jesi said...

These all are notable facts… I stick with responsive website design for my business. With the mobile marketing is at its peak stage, having website that goes comfy on all devices will help your business. You can check my website for more details on the importance of responsive website design. PHP Training Institute in Chennai | Best PHP training in Chennai | PHP Training Institute in Chennai