Read one line of text from a text file with PHP
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:
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:
Then we gets the text of the line of the text file with PHP function fgets();
Now we print the line of text we get from the text file to the screen:
At last we close the file with PHP function fclose();
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.