PHP How to write to a specific line in a file? [closed]

泪湿孤枕 提交于 2019-12-11 07:48:17

问题


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");

回答1:


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
 */



回答2:


Something like the following maybe?

$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");


来源:https://stackoverflow.com/questions/26631633/php-how-to-write-to-a-specific-line-in-a-file

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!