1. Computing

Read & Return Data From Files Into PHP

By , About.com Guide

4 of 5

Using fgets () in PHP
Fgets () is used to read the data from a file one line at a time starting from the pointer. It defaults to only reading the first 1024 bytes of a line, however you can set this variable higher or lower if you wish. If your file is not separated with line breaks, this is not the right function to use.
 <?php 
 $YourFile = "YourFile.txt"; 
 $handle = fopen($YourFile, 'r'); 
 while (!feof($handle)) 
 { 
 $Data = fgets($handle, 256); 
 print $Data; 
 print "<p>"; 
 } 
 fclose($handle); 
 ?> 
What this code does first is open the file YourFile.txt. It then enters into a loop that will read up to 256 bytes of the file line, print the contents of the line, print an HTML paragraph break, and then repeat this with the next line until it reaches the end of the file (foef).
  1. About.com
  2. Computing
  3. PHP / MySQL
  4. Advanced PHP
  5. Fgets - Fgets PHP - Fgets Tutorial

©2013 About.com. All rights reserved.