Reading from a File

Contact Us or call 1-877-932-8228
Reading from a File

Reading from a File

Opening a file for reading involves three steps:

  1. Open the file.
  2. Read the file.
  3. Close the file.


fgets() is used to read a file one line at a time. It requires one argument: the resource or "handle" for the file and accepts a second argument: the length of the line. It will continue reading the line until the length - 1 have been read or it reaches the end of the line or the end of the file. If the second argument is not included, it will continue reading until it reaches the end of the line.

Examine the file shown below.

Code Sample:

Nancy	Davolio	Sales Representative
Andrew	Fuller	Vice President, Sales
Janet	Leverling	Sales Representative
Margaret	Peacock	Sales Representative
Steven	Buchanan	Sales Manager
Michael	Suyama	Sales Representative
Robert	King	Sales Representative
Laura	Callahan	Inside Sales Coordinator
Anne	Dodsworth	Sales Representative

Employees.txt is a tab-delimited text file. Each line is formatted as follows:


The file is divided into "columns" using tabs (\t) and each "row" is separated by a newline character (\n). The code below opens Employees.txt, reads and displays each line, and closes the file.

Code Sample:

<meta charset="UTF-8">
	$myFile = @fopen("Employees.txt", 'r');
	if (!$myFile)
		echo '<p>Cannot open file.';
		while (!feof($myFile))
			$employee = fgets($myFile, 999);
			echo $employee.'<br>';
Other options for reading from files
Function Description
fgetss() Like fgets() but it strips out HTML and PHP tags.
fgetcsv() Like fgets() but it splits the file on a specified delimiter rather than a newline character.
readfile() Opens a file, sends its contents to the browser, and closes the file.
file() Opens a file, splits it into an array on newline characters, and closes the file.