Search code examples
phpfopenfwrite

PHP How to write to a specific line in a file?


I need to write to a specific line in the file without emptying php code.

$file="variables.php";
$linecount = 0;
$handle = fopen($file, "r");
while(!feof($handle)){
  $line = fgets($handle);
  $linecount++;
}

$linecount=$linecount-1;
echo $linecount;

fclose($handle);


$handle = fopen($file, "a+");
fwrite($handle, "$newvar=null". "\n");

Solution

  • You can use file to read the contents of the file into an array (with line numbers) and just alter the lines. For example;

    <?php
    
    /**
     * File contents before
     Line 1
     Line 2
     Line 3
     */
    
    $file = "variables.php";
    $content = file($file); //Read the file into an array. Line number => line content
    foreach($content as $lineNumber => &$lineContent) { //Loop through the array (the "lines")
        if($lineNumber == 2) { //Remember we start at line 0.
            $lineContent .= "Hello World" . PHP_EOL; //Modify the line. (We're adding another line by using PHP_EOL)
        }
    }
    
    $allContent = implode("", $content); //Put the array back into one string
    file_put_contents($file, $allContent); //Overwrite the file with the new content
    
    /**
     * File contents after
     Line 1
     Line 2
     Line 3
     Hello World
     */