2017-02-26 22 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

使用一个循环,阅读从一个线,写入,另一方面也与计数 –

+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

你能不能把它写在一行请 –

+0

stream_get_line包括行结尾 - 如果你看到“一行”,那么你的文本编辑器可能不支持unix行结尾。但是,因为这是被复制,你会期望看到在你的源文件 – Theo

+0

相同的问题,谢谢,我想通了。 –

相关问题