开发者

php - fgets - read first line twice?

i have a while loop that FGETS through an external file and then executes function a() over each line.

what i want to do is to first look at the first line. if the line meets certain criteria, I want to execute function b() with it and then have the while loop work the a() function over lines 2+.

if the first line does NOT match the criteria, then i want the while loop to work the a() function over lines 1+.

is this possible without开发者_如何转开发 having to close and reopen the file again?


After you read first line you can reset file pointer to start of file, using fseek

fseek($file,0);


Absolutely. Here's one way:

if (($line = fgets(...)) !== false)
{
  if (meets_criteria($line))
  {
    b($line);
  }
  else
  {
    a($line);
  };
  while (($line = fgets(...)) !== false)
  {
    a($line);
  };
};

Feel free to fix any errors found.


If the file is not too big to be read into memory, you can just use file() instead of FGETS like this

$lines = file('the-data.file');
foreach($lines as $line){
 if (meets_criteria($line))
  {
    b($line);
    a(implode(array_slice($lines,2)));
  }
  else
  {
    a(implode($lines));
  };
};
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜