2010-12-10 64 views
3

除了前20使用PHP從文本文件中的每一行除外的所有行?刪除除了前20使用PHP

+4

你應該做一些自己的研究以及。本網站補充其他資源,而不是其他互聯網的替代品。人們會很樂意提供幫助,但是,您還必須採取一些措施來幫助自己。 – DMin 2010-12-10 15:03:12

回答

5

對於內存高效的解決方案,你可以使用

$file = new SplFileObject('/path/to/file.txt', 'a+'); 
$file->seek(19); // zero-based, hence 19 is line 20 
$file->ftruncate($file->ftell()); 
+2

+1,第一個非常優雅。 – codaddict 2010-12-10 15:29:30

0

道歉,錯讀的問題...

$filename = "blah.txt"; 
$lines = file($filename); 
$data = ""; 
for ($i = 0; $i < 20; $i++) { 
    $data .= $lines[$i] . PHP_EOL; 
} 
file_put_contents($filename, $data); 
+1

我想這會給你一個文件,但是*前20行。如果我理解正確,@Ahsan只需要*第一個20. – 2010-12-10 15:05:40

+0

我的不好,代碼修改! – fire 2010-12-10 15:08:18

+0

這看起來更好,但是你最好讓那個$ i <20,否則你會閱讀21行:)你有正確的想法。 – 2010-12-10 15:08:58

7

如果加載在內存中的整個文件是可行的,你可以這樣做:

// read the file in an array. 
$file = file($filename); 

// slice first 20 elements. 
$file = array_slice($file,0,20); 

// write back to file after joining. 
file_put_contents($filename,implode("",$file)); 

一個更好的解決辦法是使用功能ftruncate其中文件句柄和文件的新大小以字節爲單位,如下所示:

// open the file in read-write mode. 
$handle = fopen($filename, 'r+'); 
if(!$handle) { 
    // die here. 
} 

// new length of the file. 
$length = 0; 

// line count. 
$count = 0; 

// read line by line.  
while (($buffer = fgets($handle)) !== false) { 

     // increment line count. 
     ++$count; 

     // if count exceeds limit..break. 
     if($count > 20) { 
       break; 
     } 

     // add the current line length to final length. 
     $length += strlen($buffer); 
} 

// truncate the file to new file length. 
ftruncate($handle, $length); 

// close the file. 
fclose($handle); 
+0

你不需要知道第20個\ n的字節數呢? – Patrick 2010-12-10 15:15:44

+0

我對fopen()不夠熟悉,至於它是否也將整個文件放入內存中,但如果fopen()使用較少的內存,則可以將其與fgets()一起用於前二十行 – Patrick 2010-12-10 15:18:37

0

喜歡的東西:

$lines_array = file("yourFile.txt"); 
$new_output = ""; 

for ($i=0; $i<20; $i++){ 
$new_output .= $lines_array[$i]; 
} 

file_put_contents("yourFile.txt", $new_output); 
+1

使用file()將內容讀入數組,以便不必手動分解()數據。 – 2010-12-10 15:07:15

+0

謝謝,我會更新我的答案。 – 2010-12-10 15:28:05

0

這應該工作以及沒有巨大的內存使用

$result = ''; 
$file = fopen('/path/to/file.txt', 'r'); 
for ($i = 0; $i < 20; $i++) 
{ 
    $result .= fgets($file); 
} 
fclose($file); 
file_put_contents('/path/to/file.txt', $result);