【问题标题】:PHP: clear a text file if it exceeds 50 lines [closed]PHP:如果文本文件超过 50 行,则清除它[关闭]
【发布时间】:2013-05-07 19:35:46
【问题描述】:

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

这是我目前所拥有的。

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

【问题讨论】:

  • count file() 语法无效...?!
  • 试试count(file($file))
  • 同上brbcoding's 建议 ;-)
  • @brbcoding,你应该已经发布了答案。
  • @Starx 这样的语法错误应该被删除 IMO...这并不是一个对 SO 有任何贡献的问题。

标签: php


【解决方案1】:
$file = 'idata.txt';
$lines = count(file($file));
if ($lines > 50){
$fh = fopen( 'idata.txt', 'w' );
fclose($fh);
}

【讨论】:

  • 太糟糕了,我没有为 cmets 获得积分:P
  • @brbcoding 太糟糕了,我们无法拆分/分享积分。称之为“合资企业”;-)
  • 是的,我必须尝试过应该抓住它。谢谢!
  • @ToxicMouse 这种方式将文件加载到内存中。解决问题的方法非常冒险。非常大的文件需要很长时间才能给count(file($file))
  • @ToxicMouse 不客气。
【解决方案2】:

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

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

应该完成这项工作,而不是内存中的整个文件。

【讨论】:

    【解决方案3】:

    count 的语法错误。将这一行 count file($file); 替换为

    count(file($file));

    【讨论】:

    • 这个确切的答案就在您的下方。 5 分钟前发布。
    • 5分钟前发布的答案只包含固定代码。连一句解释都没有。想要指出确切的错误,这就是为什么发布答案。
    【解决方案4】:

    您的语法有错误,应该是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++;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-06-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-02-21
      • 2013-03-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多