2015-12-04 44 views
2

我有一個很大的文件「file.txt的」在一個大文件替換特定行(PHP)

我想從文件讀取一個特定的路線,改變的東西,然後寫該行放回原處在文件中。

由於它是一個大文件,我不想在讀取或寫入過程中讀取整個文件,我只想訪問那一行。

這是我使用來獲取所需的線路什麼:

$myLine = 100; 
$file = new SplFileObject('file.txt'); 
$file->seek($myLine-1); 
$oldline = $file->current(); 
$newline=str_replace('a','b',$oldline); 

現在我該怎麼寫這個價值換行符替換該文件在舊線?

回答

0

您可以使用此功能:PHP what is the best way to write data to middle of file without rewriting file

function injectData($file, $data, $position) { 
    $temp = fopen('php://temp', "rw+"); 
    $fd = fopen($file, 'r+b'); 

    fseek($fd, $position); 
    stream_copy_to_stream($fd, $temp); // copy end 

    fseek($fd, $position); // seek back 
    fwrite($fd, $data); // write data 

    rewind($temp); 
    stream_copy_to_stream($temp, $fd); // stich end on again 

    fclose($temp); 
    fclose($fd); 
} 

從我得到了它