Read one line of text from a text file with PHP

Posted by Shek on May 23, 2008 under PHP | Be the First to Comment | Total View: 6,955 views

In some cases, rather than using the database to store data, you can also use a text file “.txt” to store a record. Maybe the record is a name, a number or a line of text. To read the line in the text file, I have create an example to show you how to do so:

I have created a text file “atextfile.txt” and it has a line of text inside “Hello world!!”.
I have created a php file called “test.php” and has codes to read the line of test from the text file and print it out onto the screen.
The two files are in the same directory.

For test.php file:

First I have created a PHP variable to hold the name of the text file:

$tempfile="atextfile.txt";

Then we have to use a PHP function fopen() to open and read the text of the text file, “r” means to read the file:

$tempvar=fopen($tempfile,"r");

Then we gets the text of the line of the text file with PHP function fgets();

$temptext=fgets($tempvar);

Now we print the line of text we get from the text file to the screen:

echo $temptext;

At last we close the file with PHP function fclose();

fclose($tempvar);

All together we have:

1
2
3
4
5
6
7
<?php
$tempfile="atextfile.txt"; 
$tempvar=fopen($tempfile,"r");
$temptext=fgets($tempvar);
echo $temptext;
fclose($tempvar);
?>

When you run the test.php file, on your screen should have “Hello world!!”.
Notice that the PHP function fgets() can only read a line of text of a text file.

Not what you want? Try a Search

Add A Comment

*