PHP:清除超过50行的文本文件


PHP: clear a text file if it exceeds 50 lines

好的,我错过了什么?如果文件超过50行,我正在尝试清除文件。

这是我目前所掌握的。

$file = 'idata.txt';
$lines = count file($file);
if ($lines > 50){
$fh = fopen( 'idata.txt', 'w' );
fclose($fh);
}
$file = 'idata.txt';
$lines = count(file($file));
if ($lines > 50){
$fh = fopen( 'idata.txt', 'w' );
fclose($fh);
}

如果文件真的可以很大,你最好循环:

$file="verylargefile.txt";
$linecount = 0;
$handle = fopen($file, "r");
while(!feof($handle)){
  $line = fgets($handle);
  $linecount++;
  if(linecount > 50)
  {
      break;
  }
}
应该完成这项工作,而不是在内存中的整个文件。

count语法错误。将count file($file);替换为

count(file($file));

你有一个语法错误,它应该是count(file($file));使用这种方法不建议使用较大的文件,因为它将文件加载到内存中。因此,在大文件的情况下,它将没有帮助。下面是解决这个问题的另一种方法:

$file="idata.txt";
$linecount = 0;
$handle = fopen($file, "r");
while(!feof($handle)){
  if($linecount > 50) {
      //if the file is more than 50
      fclosh($handle); //close the previous handle
      // YOUR CODE
      $handle = fopen( 'idata.txt', 'w' ); 
      fclose($handle);  
  }
  $linecount++;
}