PHP MySQL Tutorial
Learn PHP and MySQL

Reading a File Using PHP

Page Details

Published by:
admin
on 12-20-2008
4 people found this article useful.

100% of people found this useful
Reading a File Using PHP

A simple method for reading a file is to use the file() function which  will return an array containing each line of the file. Here's an example :

// open the file and save each line as an array entry in $content
$content = file('myfile.txt');

// count how many lines in the file
$numLines = count($content);

// loop through all the lines
for ($i = 0; $i < $numLines; $i++) {
   // each line ends with a newline character
   // you may want to get rid of this first
   // using trim()
   $line = trim($content[$i]);

   // do whatever you want to do with that line
   // ...

}


The second alternative is using the fopen() and read one line at a time using a while loop like this :


// open the log file and check if the it's opened successfully
if (!($fp = fopen('myfile.txt', 'r'))) {
   die('Cannot open file');
}

// keep fetching a line from the file until end of file
while ($line = fgets($fp, 4096)) {
   // trim to remove new line character at the end of line
   $line = trim($line);

   // do whatever you want to do with that line
   // ...
}
Powered by Community Server (Non-Commercial Edition), by Telligent Systems