Saturday, 15 January 2011

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



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

i need write specific line in 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");

you can utilize file read contents of file array (with line numbers) , alter lines. example;

<?php /** * file contents before line 1 line 2 line 3 */ $file = "variables.php"; $content = file($file); //read file array. line number => line content foreach($content $linenumber => &$linecontent) { //loop through array (the "lines") if($linenumber == 2) { //remember start @ line 0. $linecontent .= "hello world" . php_eol; //modify line. (we're adding line using php_eol) } } $allcontent = implode("", $content); //put array 1 string file_put_contents($file, $allcontent); //overwrite file new content /** * file contents after line 1 line 2 line 3 hello world */

php fopen fwrite

No comments:

Post a Comment