2017-02-26 8 views
0

こんにちは私はこのコードを持っている:最初の10000行をファイルから読み込んで別のファイルに書き込む方法は? PHP

 file1 = file_get_contents("read.txt"); 
$path2 = "write.txt"; 
$file2 = file_get_contents($path2); 
if ($file1 !== $file2){ 
    file_put_contents($path2, $file1); 
    echo "working"; 
} 

は、どのように私はread.txtファイルから最初の10000行以上を取得し、write.txtでそれらを書くことができますか?

+1

ファイルを()配列を作成し、配列はカウンターで、 – nogad

+0

は他への書き込み、1から行を読んで、ループを使用してインデックスされます –

+0

ジェネレータを使用する方がよいでしょうhttp://php.net/manual/en/language.generators.overview.php – bxN5

答えて

0

ファイル全体を読むにはさまざまな方法がありますが、ストリームを使用して必要なデータだけを読み込むほうがよいでしょう。

<?php 
$source="file.txt"; 
$destination="file2.txt"; 
$requiredLines=10000; 

//compare the modification times, if source is newer than destination - then we do our work 
if(filemtime($source)>filemtime($destination)){   
    //work out maximum length of file, as one line may be the whole file. 
    $filesize = filesize($source); 

    //open file for reading - this doesnt actually read the file it allows us to "stream" it 
    $sourceHandle = fopen($source, "r"); 

    //open file for writing 
    $destinationHandle = fopen($destination, "w"); 

    $linecount=0; 
    //loop through file until we reach the end of the file (feof) or we reach the desired number of lines 
    while (!feof($sourceHandle) && $linecount++<$requiredLines) { 
     //read one line 
     $line = stream_get_line($sourceHandle, $filesize, "\n"); 
     //write the line 
     fwrite($destinationHandle,$line); 
    } 
    //close both files 
    fclose($sourceHandle); 
    fclose($destinationHandle); 
} 

あなたがここにストリーム上でより多くの情報を見つけることができます:Understanding PHP Streams

+0

あなたはそれを1行で書かないようにすることができますか? –

+0

stream_get_lineには行末が含まれています - "1行"が表示されている場合、テキストエディタはUNIX行の終わりをサポートしません。しかし、これがコピーされているので、あなたのソースファイルに同じ問題があると思うでしょう。 – Theo

+0

私は考え出しました。 –

関連する問題