How to read data line by line from text file in php?

The code posted above from Payload works great. I'd like to add something to this because others might run into the same problem. I used your code and was trying to compare a value with a $line that was fetched from the .txt file. Even though I know my keyword matches a line I kept getting an error. this is an example of the code...

textfile.txt content example:

text1
text2
keyword
text3

$keyword = 'keyword';

while($line = fgets($txt_file)) {

    if (substr_compare($line, $keyword, 0) === 0) { 
        $value = $line;
    }
}

echo $value; // returns nothing because the if statement was false

The problem is each $line is carrying a new line at the end of it. But in my case I just used enter for a new line when creating the .txt file, it's not specified with something like "\n" or idk "\r\n". Anyways, if you're running into the same problem be sure to trim() the $line before you work with it to get rid of any whitespace or in this case the new line or you might keep running into errors. the shortest and easiest way to do this without getting weird results is to simply trim it right in the while statement like this...

while($line = trim(fgets($txt_file))) {
    
    if (substr_compare($line, $keyword, 0) === 0) { 
        $value = $line;
    }
} 

echo $value; // result: keyword

and yes i did get some weird results trying to throw the trim() around $line inside the substr_compare() function, even though the if statement result was TRUE the $value would have a result of " keyword " with a space on the beginning and end of the keyword. weird stuff...


In this chapter we will teach you how to open, read, and close a file on the server.


PHP Open File - fopen()

A better method to open files is with the fopen() function. This function gives you more options than the readfile() function.

We will use the text file, "webdictionary.txt", during the lessons:

AJAX = Asynchronous JavaScript and XML
CSS = Cascading Style Sheets
HTML = Hyper Text Markup Language
PHP = PHP Hypertext Preprocessor
SQL = Structured Query Language
SVG = Scalable Vector Graphics
XML = EXtensible Markup Language

The first parameter of fopen() contains the name of the file to be opened and the second parameter specifies in which mode the file should be opened. The following example also generates a message if the fopen() function is unable to open the specified file:

Example

$myfile = fopen("webdictionary.txt", "r") or die("Unable to open file!");
echo fread($myfile,filesize("webdictionary.txt"));
fclose($myfile);
?>

Run example »

Tip: The fread() and the fclose() functions will be explained below.

The file may be opened in one of the following modes:

ModesDescription
r Open a file for read only. File pointer starts at the beginning of the file
w Open a file for write only. Erases the contents of the file or creates a new file if it doesn't exist. File pointer starts at the beginning of the file
a Open a file for write only. The existing data in file is preserved. File pointer starts at the end of the file. Creates a new file if the file doesn't exist
x Creates a new file for write only. Returns FALSE and an error if file already exists
r+ Open a file for read/write. File pointer starts at the beginning of the file
w+ Open a file for read/write. Erases the contents of the file or creates a new file if it doesn't exist. File pointer starts at the beginning of the file
a+ Open a file for read/write. The existing data in file is preserved. File pointer starts at the end of the file. Creates a new file if the file doesn't exist
x+ Creates a new file for read/write. Returns FALSE and an error if file already exists


PHP Read File - fread()

The fread() function reads from an open file.

The first parameter of fread() contains the name of the file to read from and the second parameter specifies the maximum number of bytes to read.

The following PHP code reads the "webdictionary.txt" file to the end:

fread($myfile,filesize("webdictionary.txt"));


PHP Close File - fclose()

The fclose() function is used to close an open file.

It's a good programming practice to close all files after you have finished with them. You don't want an open file running around on your server taking up resources!

The fclose() requires the name of the file (or a variable that holds the filename) we want to close:

$myfile = fopen("webdictionary.txt", "r");
// some code to be executed....
fclose($myfile);
?>


PHP Read Single Line - fgets()

The fgets() function is used to read a single line from a file.

The example below outputs the first line of the "webdictionary.txt" file:

Example

$myfile = fopen("webdictionary.txt", "r") or die("Unable to open file!");
echo fgets($myfile);
fclose($myfile);
?>

Run example »

Note: After a call to the fgets() function, the file pointer has moved to the next line.


PHP Check End-Of-File - feof()

The feof() function checks if the "end-of-file" (EOF) has been reached.

The feof() function is useful for looping through data of unknown length.

The example below reads the "webdictionary.txt" file line by line, until end-of-file is reached:

Example

$myfile = fopen("webdictionary.txt", "r") or die("Unable to open file!");
// Output one line until end-of-file
while(!feof($myfile)) {
  echo fgets($myfile) . "
";
}
fclose($myfile);
?>

Run example »


PHP Read Single Character - fgetc()

The fgetc() function is used to read a single character from a file.

The example below reads the "webdictionary.txt" file character by character, until end-of-file is reached:

Example

$myfile = fopen("webdictionary.txt", "r") or die("Unable to open file!");
// Output one character until end-of-file
while(!feof($myfile)) {
  echo fgetc($myfile);
}
fclose($myfile);
?>

Run example »

Note: After a call to the fgetc() function, the file pointer moves to the next character.


Complete PHP Filesystem Reference

For a complete reference of filesystem functions, go to our complete PHP Filesystem Reference.


PHP Exercises



How read a specific line from a file in PHP?

php $myFile = "4-24-11. txt"; $fh = fopen($myFile, 'r'); $theData = fgets($fh); fclose($fh); echo $theData; ?> ...
Note: that should be $lines[1] ... .
Thanks man! ... .
if the file size is huge, this solution will be slow and occupying a lot memory. ... .
Still, 40+ upvotes?.

How do I read the contents of a PHP file?

The file_get_contents() reads a file into a string. This function is the preferred way to read the contents of a file into a string. It will use memory mapping techniques, if this is supported by the server, to enhance performance.

Which PHP function reads a single line from a file?

PHP fgets() function is used for reading single line from file This function takes two arguments as described below. 2. Length Optional parameter, specifies number of bytes to read from file.

What is the use of fopen () function in PHP?

The fopen() function opens a file or URL. Note: When writing to a text file, be sure to use the correct line-ending character! Unix systems use \n, Windows systems use \r\n, and Macintosh systems use \r as the line ending character.