Jump to content

How do I read a text file...2 lines at a time?


vexusdev

Recommended Posts

I have tried numerous different codes and I can't seem to get this working right.

 

I want to read a text file say 100 lines at a time.

 

If you guys need a little bit of clarification.

 

 

say I have a text file with

 

Nick

Bob

John

Larry

Ashley

Britney

Tom

Lisa

Joshua

 

Say I need to process that list 2 lines at a time.

 

First chunk [Nick,Bob]

Second chunk [John,Larry]

Third chunk [Ashley,Britney]

 

Does anyone have the slightest idea of how to accomplish that?

$lines = file('file.txt');

 

for($i=0; $i<2; $i++)

{

  echo $lines[$i];

}

 

 

Yeh but that sort of rules out large files.. file() has size limits and its not efficient because we are loading the whole file into the memory right off the bat.

if u have huge mounts of data why not use databases?

 

Well because the user will be uploading a list and this list will be converted(by querying a database) and then rewriting to another text file.

 

Also the code that you wrote.. won't that only read the first 2 lines of the file? I need to read the whole file 2 lines at a time. I just can't grasp how to accomplish this because of my limited knowledge.

$fh = fopen('filename','rb');
while(!feof($fh)) {
$line1 = fgets($fh);
if(!feof($fh)) {$line2 = fgets($fh);}
//do something with these two lines
}

 

[edited]

 

Its fgets obviously, not fread

 

Thank you, say I wanted to expand that to read 100 lines at a time is it possible?

 

What if i made a loop from 1 to 100 with fgets inside the while loop and insert the data into an array?

 

 

Of course you can do it like that.

 

One more question.

 

say i did this:

 

while

fgets

fgets

fgets

 

Thats not actual code of course but would that grab the line 3 times right then? then next while rotation be at 4.. ready to grab 4,5,6?

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.