fwrite in a certain PHP line

Asked

Viewed 696 times

1

I want to write a particular code on a particular line of a PHP file.

<?php
$arquivo_origem = "client.php";
$arquivo_destino = "copiado.php";

if (copy($arquivo_origem, $arquivo_destino)){
    echo "Sucesso!";

}


$teste = "Eu sei";

$handle = fopen( $arquivo_destino, 'a+' );

$ler = fwrite( $handle, $teste );

// Fecha o arquivo
fclose($handle);


?>

I would like to write my variable $test on line 17 of my $file destination.

In the case as I do?

2 answers

1

You can do something like this:

<?php

$file = $arquivo_destino;
$line_looking = 16; //lembre que a contagem começa em 0

$lines = file($file, FILE_IGNORE_NEW_LINES);
$lines[$line_looking] = 'Linha substituida';
file_put_contents($file, implode("\n", $lines));

An example -> http://ideone.com/9XtaS5

  • Good Morning, in my case I wanted to replace the line, but my complete code is like this: http://pastebin.com/Za4q4Sxq However it creates the file pastes the code but does not replace the line, can indicate me the error?

  • possibly because you are opening the file twice, the first in append mode on line 14 and then on line 21, remove line 14 ($Handle = fopen( $arquivo_destination, 'a+' );) and line 26 ($Handle = fopen( $arquivo_destination, 'a+' );)

  • Good Morning, It’s still the same print the file but it doesn’t replace the line.

  • here works of good

  • you can see an example here http://ideone.com/9XtaS5

1

Complementing @Adir Kuhn’s reply, if you need to insert in the middle and not replace, you can do so:

$arquivo = '/dir/ate/arquivo.ext';
$numero_linha = 17;
$conteudo_linha = 'teste';

$linhas = file($arquivo); // lê o arquivo na forma de array (cada linha é um elemento)
$final_array = array_splice($linhas, $numero_linha-1); // corta array ($linhas fica com a primeira parte; array_splice retorna a parte cortada)
$linhas[] = $conteudo_linha . "\n"; // adiciona após a posição cortada
$linhas = array_merge($linhas, $final_array); // junta novamente
file_put_contents($arquivo, $linhas);
  • In case I wish to replace, please see my comment below.

Browser other questions tagged

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