[SOLVED] how do i read a text file line by line

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
pelegk2
Forum Regular
Posts: 633
Joined: Thu Nov 27, 2003 5:02 am
Location: Israel - the best place to live in after heaven
Contact:

how do i read a text file line by line

Post by pelegk2 »

and not asa whole stirng?
User avatar
ol4pr0
Forum Regular
Posts: 926
Joined: Thu Jan 08, 2004 11:22 am
Location: ecuador

Post by ol4pr0 »

Code: Select all

$lines ='0';
if ($fh = fopen('textfile.txt','r')) {
while (!feof($fh)) {
if (fgets($fh,1048576)) {
$lines++;
}
}
}
print $lines;
That do the trick ?
User avatar
launchcode
Forum Contributor
Posts: 401
Joined: Tue May 11, 2004 7:32 pm
Location: UK
Contact:

Post by launchcode »

Is there a specific reason to need to read it line by line? because it takes a lot longer to do. Why not just read it into a string and then split it - or into an array and loop through it?
User avatar
m3mn0n
PHP Evangelist
Posts: 3548
Joined: Tue Aug 13, 2002 3:35 pm
Location: Calgary, Canada

Post by m3mn0n »

file_get_contents()
then explode() by \n or \r\n
foreach() through it all to display it
User avatar
pickle
Briney Mod
Posts: 6445
Joined: Mon Jan 19, 2004 6:11 pm
Location: 53.01N x 112.48W
Contact:

Post by pickle »

It's quite easy actually, just call

Code: Select all

$file_contents = file($filename);
and $file_contents will be an array with each element containing a line of the file.
Real programmers don't comment their code. If it was hard to write, it should be hard to understand.
redmonkey
Forum Regular
Posts: 836
Joined: Thu Dec 18, 2003 3:58 pm

Post by redmonkey »

User avatar
pelegk2
Forum Regular
Posts: 633
Joined: Thu Nov 27, 2003 5:02 am
Location: Israel - the best place to live in after heaven
Contact:

Post by pelegk2 »

thnaks all of u
i have used file()
so simple to use

and YEs launchcode there is a reason to read each line by line
User avatar
launchcode
Forum Contributor
Posts: 401
Joined: Tue May 11, 2004 7:32 pm
Location: UK
Contact:

Post by launchcode »

Ok just wondered - because file() doesn't read it line-by-line at all ;)
Post Reply