How can I edit a specific line in a file? There we $fil = @file($user); $count = $fil[5]; 0, I get zero using $fil = @file($user); $count = $fil[5]; $fil = @file($user); $count = $fil[5]; , now I need to delete this 0 and instead write 1 to the file, i.e. increase the value by 1.

  • And what does a soma line look like in a file? Bring more and more details - Vanya Avchyan
  • @VanyaAvchyan, just 0. There is nothing else. On the other lines there are other data, so the file cannot be completely cleaned. - NTP
  • Edit the question by adding the latest information. I correctly understood: do you have lines in the file that are separated by enter (\ r \ n), and one line of them is the number 0? - Vanya Avchyan
  • If there is only one line and only one digit in this line, the file_get_contents () and file_put_contents () functions will suffice you fens
  • @VanyaAvchyan, yes, lines of the order of 100, separated by \ n, and 6 line is 0. Here it needs to be incremented by one for each function call. - NTP

2 answers 2

We use two great functions file and file_put_contents

Suppose we have a test.txt file with the following lines:

 0 a b c d 

PHP code:

 <?php function visitCounter() { $file = 'test.txt' ; $array = file( $file ); //файл в котором надо заменить строку, разбираем в массив построчно if($array) { //предполагаю по вашим ответам что число счетчика находится на //первой строке ,если же нет то укажите его номер в квадратных //скобках($array[n] ...) учитывая что отсчет идет от нуля $array[0] =((int)$array[0] + 1) . "\n"; // увеличиваем первый элемент массива(условно говоря первую строку файла) на единицу. } file_put_contents( $file, $array ); // записываем обратно в файл } visitCounter(); ?> 

    I assume you know the line number in advance.

    index.php

     <? $lines = file('./filename.txt');//преобразуем файл в массив $count = $lines[1]; $lines[8] = strval($count+1)."\n";//инкрементируем наш элемент массива и преобразуем его в строку file_put_contents("./file.txt", $lines);//пишем строку в файл $lines = file('./file.txt'); print_r($lines); 

    filename.txt

     строка0 0 строка2 строка3 строка4 
    • Nothing happens when I run a file with php code. And when, instead of <? I write <? php pops up the following error: Notice: A non well formed numeric value encountered in C: \ xampp \ htdocs \ indx.php on line 4 - user216109
    • @Sergey, New E_WARNING and E_NOTICE levels errors were added in php 7.1 when using invalid strings with operators waiting for numbers (+ - * / **% << >> | & ^) and their equivalents with assignment. An E_NOTICE level error is issued when a line starts with numbers, but then it does not contain numeric characters, and an E_WARNING level error is issued when the line does not contain any numbers at all. Since your array element with zero is actually a string containing 0 and a line break. This is just a warning, it does not affect the operation of the script. - Gleb Ostrikov