2013-05-13 48 views
0

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

这是我到目前为止。

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

'count file()'是无效的语法...?! – deceze 2013-05-13 17:22:47

+3

尝试'计数(文件($文件))' – brbcoding 2013-05-13 17:23:03

+0

同上上'brbcoding's'建议;-) – 2013-05-13 17:24:42

回答

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

太糟糕了,我没有得到意见分:P – brbcoding 2013-05-13 17:28:32

+1

@brbcoding太糟糕了,我们无法分割/分享积分。称它为“合资企业”;-) – 2013-05-13 17:33:35

+0

是的,做到了,我必须尝试应该抓住这一点。谢谢你! – ToxicMouse 2013-05-13 17:40:50

0

的语法计数是wrong.Replace此行count file($file);通过

count(file($file));

+0

这个确切的答案就在你的下方。提前5分钟发布。 – brbcoding 2013-05-13 17:32:28

+0

5分钟前发布的答案只包含固定代码。甚至没有一个解释的单词。想要指出确切的错误,那就是为什么发布答案。 – 2013-05-13 17:35:56

0

如果文件真的可以大你更好的循环:

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

应该做这项工作,而不是整个文件在内存中。

0

你在你的语法错误,应该是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++; 
} 
相关问题