1. Home
  2. Computing & Technology
  3. PHP / MySQL

Read & Return Data From Files Into PHP

By Angela Bradley, About.com

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).
Explore PHP / MySQL
About.com Special Features

Stay connected and entertained with reviews on tips on the latest HDTVs, cellphones and more. More >

Easy ways to connect two computers for networking purposes. More >

  1. Home
  2. Computing & Technology
  3. PHP / MySQL
  4. Advanced PHP
  5. Fgets - Fgets PHP - Fgets Tutorial

©2009 About.com, a part of The New York Times Company.

All rights reserved.