当前位置: 动力学知识库 > 问答 > 编程问答 >

PHP: clear a text file if it exceeds 50 lines

问题描述:

OK, what am I missing? I am trying to clear a file if it exceeds 50 lines.

This is what I have so far.

$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);
}
网友答案:

Syntax of count is wrong.Replace this line count file($file); by

count(file($file));

网友答案:

If files really can be big you better loop:

$file="verylargefile.txt";
$linecount = 0;
$handle = fopen($file, "r");
while(!feof($handle)){
  $line = fgets($handle);
  $linecount++;
  if(linecount > 50)
  {
      break;
  }
}

Should do the job, and not the whole file in memory.

网友答案:

You have an error in your syntax, it should be count(file($file)); Using this method is not recommended for larger file as it loads the file onto the memory. Thus, it will not be helpful in case of large files. Here is another way to solve this:

$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++;
}
分享给朋友:
您可能感兴趣的文章:
随机阅读: