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

时间:2014-10-29 13:27:53

标签: 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");

2 个答案:

答案 0 :(得分:3)

您可以使用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
 */

答案 1 :(得分:0)

可能会出现以下情况?

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

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

fclose($handle);


$handle = fopen($file, "w+");
fwrite($handle, $currentData."$newvar=null". "\n");
相关问题