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()

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:

Files/Demos/Employees.txt
Nancy	Davolio	Sales Representative	ndavolio@northwind.com
Andrew	Fuller	Vice President, Sales	afuller@northwind.com
Janet	Leverling	Sales Representative	jleverling@northwind.com
Margaret	Peacock	Sales Representative	mpeacock@northwind.com
Steven	Buchanan	Sales Manager	sbuchanan@northwind.com
Michael	Suyama	Sales Representative	msuyama@northwind.com
Robert	King	Sales Representative	rking@northwind.com
Laura	Callahan	Inside Sales Coordinator	lcallahan@northwind.com
Anne	Dodsworth	Sales Representative	adodsworth@northwind.com

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

FirstName\tLastName\tTitle\tEmail\n

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:

Files/Demos/Employees.php
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>Employees</title>
</head>
<body>
<h1>Employees</h1>
<?php
	$myFile = @fopen("Employees.txt", 'r');
	
	if (!$myFile)
	{
		echo '<p>Cannot open file.';
	}
	else
	{
		while (!feof($myFile))
		{
			$employee = fgets($myFile, 999);
			echo $employee.'<br>';
		}
		fclose($myFile);
	}
?>
</body>
</html>
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.
Next