1. Computing & Technology

Discuss in my forum

Read & Return Data From Files Into PHP

By , About.com Guide

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.

©2012 About.com. All rights reserved.

A part of The New York Times Company.