您可以通过很多方式来读取整个文件,但最好使用流并只读取所需的数据。
<?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
文件()创建一个数组,数组的索引 – nogad
使用一个循环,阅读从一个线,写入,另一方面也与计数 –
更好地使用发电机http://php.net/manual/en/language.generators.overview.php – bxN5