如何从文件中读取前10000行并将其写入另一行? PHP

时间:2017-02-26 22:40:48

标签: php file

您好我有这段代码:

      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 个答案:

答案 0 :(得分: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