PHP 如何写入文件中的特定行?

Caz*_*azs 1 php fopen fwrite

我需要在不清空 php 代码的情况下写入文件中的特定行。

$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");
Run Code Online (Sandbox Code Playgroud)

ʰᵈˑ*_*ʰᵈˑ 5

您可以使用file将文件的内容读入一个数组(带有行号)并更改行。例如;

<?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
 */
Run Code Online (Sandbox Code Playgroud)