2010-12-10 13 views
3

テキストファイルからphpを使用して最初の20行を除くすべての行を削除するにはどうすればよいですか?削除最初の20行以外のすべての行をPHPを使用して

+4

あなたは自分でいくつかの研究を行うべきです同じように。このウェブサイトは他のリソースを補完し、インターネットの他の部分に代わるものではありません。人々は助けが好きですが、あなたも自分自身を助けるためにいくつかの措置を取る必要があります。 – DMin

答えて

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

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個のみを望んでいます。 –

+0

私の悪い、コードが修正されました! – fire

+0

これは良く見えますが、$ i <20にするか、21行読むのが良いでしょう:)あなたは正しい考えを持っています。 –

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

+0

fopen()はファイル全体をメモリに格納するかどうかについてはあまりよく分かりませんが、fopen()のメモリ使用量が少ない場合は最初の20行でfgets()を使用できます。 – Patrick

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()を使って内容を配列に読み込むので、手動でデータを分解()する必要はありません。 –

+0

ありがとう、私は私の答えを更新します。 –

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); 
関連する問題