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

Read & Return Data From Files Into PHP

By Angela Bradley, About.com

5 of 5

Using file () in PHP

File () is similar to fgets in that it reads the data one line at a time, however it returns it all at once into an array. The array contains the line number, and the data corresponding to each line number starting with 0. If you want to do more than simply echo the data, having it in an array will provide much more flexibility making file () more useful than fgets ().
<?php
$lines = file('YourFile.txt');
foreach ($lines as $line_num => $line)
{
print "<font color=red>Line #{$line_num}</font> : " . $line . "<br />\n";
}
?>
What this code does first is put the contents of YourFile.txt into the array called $lines. It then enters into a loop which prints each line number in red, followed by the line contents, and repeats until all lines have been printed.
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. File - File PHP - File PHP Tutorial

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

All rights reserved.