Page 1 of 1

reading a file line by line

Posted: Mon Aug 15, 2005 4:19 am
by pelegk2
how do u i read a file line by line and not at once?

[i have in the past posted here a question about it,and found the url using the search but i get the message that the message dosent exist any more]

thnaks i advance
peleg

Posted: Mon Aug 15, 2005 4:46 am
by anjanesh

Posted: Mon Aug 15, 2005 5:06 am
by bladecatcher
I'll try but be warned newbie lurks beneath.

Code: Select all

$wpage = fopen("www/myfile.txt", "r");
while(!feof($wpage)){
	$readline = trim(fgetss($wpage, 1024)) ;
                //do stufff
}
fclose($wpage);

Posted: Mon Aug 15, 2005 11:58 am
by trdesigns
I'm not exactly sure whether this is what you need, but file() will read the file into an array, each element of which will be one line of the file.

Posted: Mon Aug 15, 2005 2:11 pm
by josh
Yeah but file() reads the entire file, he might only want the first X lines, or he might want to stop reading when a condition is met.

Posted: Mon Aug 15, 2005 2:21 pm
by John Cartwright
jshpro2 wrote:Yeah but file() reads the entire file, he might only want the first X lines, or he might want to stop reading when a condition is met.
I don't think there is any way of reading only up to a certain point of the file. The whole file must be put into memory first.

Posted: Mon Aug 15, 2005 2:58 pm
by trdesigns
Unless there is a fixed line length, for example each line containing exactly 80 characters, I don't think that can be done without loading the whole file into memory as Jcart said.

Posted: Mon Aug 15, 2005 3:26 pm
by skhale
anjanesh wrote:fgets()
php.net wrote:fgets -- Gets line from file pointer
php.net wrote:Reading ends when length - 1 bytes have been read, on a newline (which is included in the return value), or on EOF (whichever comes first).

Posted: Mon Aug 15, 2005 3:48 pm
by josh
Jcart wrote:I don't think there is any way of reading only up to a certain point of the file. The whole file must be put into memory first.

fgets() bro...

anjanesh had said that already, I was just replying to the person who pointed out file() and I was saying file() isn't anymore efficient then doing fgets(), and fgets() is more efficient in the case of a partial file.