PHP Scripts – WordPress Tutorials

Read text file using PHP is an easy and simple method. I am going to post this for the beginners of PHP. Suppose you have text file and you may wanted to read that file and display all the information on you webpage somewhere.

I am using two php functions. fopen() and fgets(). Let’s have a look at the Script, look how easy this is to read a file and display information.

1
2
3
4
5
6
7
8
9
10
11
$filePath = "/files/myText.txt";

$res = fopen($filePath, "r");

while ( $line = fgets($res, 1000) )

{

echo $line;

}

In first line of the script, provided a path of the file, where the file exists. Then open this file and read. Fgets() will only a single line. This will keep only displaying results until the end of text file.

You can read more information about fgets() and fopen() here.

Random Posts


Categories: PHP
  • Alan Farquharson

    Why would you use this over file_get_contents() ?

    • http://www.computersneaker.com/ Mudasir Nazir

      The reason is that i am retrieving data line by line, I don’t want to mess with the contents, Because in same way i have to split my contents into strings and then i might wish to submit these strings into database.