Add Information to a file on a specific line

Asked

Viewed 1,154 times

2

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

2 answers

1


One way is to read the file and put it in one 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 line 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
  • Is there another way? My file can have 20,000+ lines, if I turn all of this into array it will give you plenty of memory and I can’t change the memory_limit of php.ini

  • @Ivanmoreira I edited the answer and put another, see if this is it.

  • I saw, but I don’t want to replace the existing lines, I want to add new lines.

  • 1

    @Ivanmoreira I’ve updated, just use .= instead of =, if you prefer to check if file exists before, use the function file_exists.

  • 1

    I understand how it works, thanks!

  • It worked perfectly, thank you very much @stderr

Show 1 more comment

0

You could use shell commands. In the example below, we use the 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).


Execution time: 0.014498949050903 (microseconds)
Memory peak: 435040 bytes
Final memory: 398224 butes

To confirm performance integrity, the same file has been increased by 8 times, 16mb.

The running time was the same.

Windows 10 Pro 64bit
PHP 7.0.5
Apache 2.4.20

To use the application sed under Windows environment: https://sourceforge.net/projects/unxutils/? source=typ_redirect

Browser other questions tagged

You are not signed in. Login or sign up in order to post.