【问题标题】:Replace a specific line in a large file (PHP)替换大文件中的特定行 (PHP)
【发布时间】:2015-12-05 04:44:07
【问题描述】:

我有一个大文件“file.txt”

我想从文件中读取一个特定的行,更改一些内容,然后将该行写回文件中的位置。

由于是一个大文件,我不想在读写过程中读取整个文件,我只想访问那一行。

这是我用来检索所需行的内容:

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

现在我该如何编写这个 $newline 来替换文件中的旧行?

【问题讨论】:

    标签: php


    【解决方案1】:

    你可以使用这个功能:

    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);
    }
    

    我来自:PHP what is the best way to write data to middle of file without rewriting file

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-18
      • 2011-03-01
      • 2022-01-15
      • 2011-09-08
      相关资源
      最近更新 更多