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
   // ...
}

Recent Comments

By: bright Posted on 08-19-2009 4:16 AM

yes is good but i need Php installation setup for xp

By: akinolafj Posted on 11-06-2009 6:22 AM

How can i display my image in Mysql  database on my web page

By: Clare Posted on 11-24-2009 4:42 PM

the complete package for developing PHP on you local machine is WAMP (currently running on my Window$ 7 box)

no advance knowledge is needed.

http://www.wampserver.com/en/

WampServer 2.0i [07/11/09]

Includes :

- Apache 2.2.11

- MySQL 5.1.36

- PHP 5.3.0

Powered by Community Server (Non-Commercial Edition), by Telligent Systems