Adding information to a file on a specified line

2

I'm using file_put_contents to create a file, but in a certain part of my process I need to add things to this file but only from line 2, I searched the PHP documentation for file_put_contents and found nothing , can anyone help me?

    
asked by anonymous 29.08.2016 / 19:24

2 answers

1

One way is to read the file and put it in array , by index you indicate the line and change the value.

$linhas = explode(PHP_EOL, file_get_contents("arquivo1.txt"));
$numeroLinha = 2;

$linhas[$numeroLinha] = "foo bar";

file_put_contents("foo.txt" , implode(PHP_EOL, $linhas));

If you prefer to read row by line:

function AdicionarLinha($arquivo, $numeroLinha, $conteudo){
    $arquivoTemporario = "$arquivo.bak";
    $linhaAtual = 0;

    $fpRead  = fopen($arquivo, 'r');
    $fpWrite = fopen($arquivoTemporario, 'w');

    try{
        if ($fpRead) {
            while (($linha = fgets($fpRead)) !== false) {
                if ($linhaAtual == $numeroLinha){
                    $linha .= $conteudo . PHP_EOL; // Para substituir, use "="
                }

                fwrite($fpWrite, $linha);
                $linhaAtual += 1;       
            }
        }
    }
    catch (Exception $err) {
        echo $err->getMessage() . PHP_EOL;
    }
    finally {
        fclose($fpRead);
        fclose($fpWrite);

        unlink($arquivo); // Para deletar o arquivo original
        rename($arquivoTemporario, $arquivo); // Para renomear o arquivo
    }
}

To use, do so:

AdicionarLinha("arquivo1.txt", 2, "foo bar"); // Adiciona "foo bar" a partir da linha 2
    
29.08.2016 / 19:41
0

You could use shell commands. In the example below, we use sed .

$file = escapeshellarg('tmp.txt');
shell_exec('sed /5/ a foo '.$file);
/*
Adiciona "foo" na quinta linha do arquivo

A letra "a" concatena (append)
Caso queira inserir numa nova linha, use letra "i" (insert)
*/

The test was done in a 2mb file, 661980 lines (660,000 lines).


Runtime: 0.014498949050903 (Microseconds)
Memory Peak: 435040 bytes
Final memory: 398224 butes

To confirm the integrity of the performance, the same file was increased by 8 times, 16mb.

The runtime was the same.

Windows 10 Pro 64bit
PHP 7.0.5
Apache 2.4.20

To use the sed application under the Windows environment: link

    
29.08.2016 / 20:28