Jump to content


Photo

Writing to a file on a specific line


  • Please log in to reply
4 replies to this topic

#1 dual_alliance

dual_alliance
  • Members
  • PipPipPip
  • Advanced Member
  • 140 posts
  • LocationNSW, Australia

Posted 10 August 2006 - 03:17 PM

I know how to write to a file.  But how do l actually write to a certain line of a file.

Example:

settings.php
// Game Details
$gameName = "namehere";  // Line 3
$gameSubName = "subnamehere";
<br />
somefile.php
$nGameName = $gameName;
$nGameSubName = $gameSubName;

$File = "settings.php";
$Handle = fopen($File, 'w');
$Data = "\$gameName = \"$nGameName\" ;\n ";
fwrite($Handle, $Data);
<br />
How would l make it so it doesn't overwrite everything but only the information on line 3?

Thanks,

dual_alliance


#2 litebearer

litebearer
  • Members
  • PipPipPip
  • Advanced Member
  • 2,357 posts
  • Locationwhite lake michigan

Posted 10 August 2006 - 04:41 PM

Easiest way would be to read the entire file into an array, where each line is an element of the array. Then you can simply edit/alter/etc the specific element/line and write the array back to file.

all the brothers were valiant!

[br][br]The truely intelligent people are not those who create the dots; rather they are they ones with the ability to connect the dots into a coherent picture

#3 dual_alliance

dual_alliance
  • Members
  • PipPipPip
  • Advanced Member
  • 140 posts
  • LocationNSW, Australia

Posted 10 August 2006 - 04:44 PM

Do you think you could please give me an example?

#4 litebearer

litebearer
  • Members
  • PipPipPip
  • Advanced Member
  • 2,357 posts
  • Locationwhite lake michigan

Posted 10 August 2006 - 04:59 PM

something like this

$handle = fopen($filename, "r");
$contents = fread($handle, filesize($filename));
fclose($handle);

the variable $contents should be an array, where each element is a line from the file.

if you wanted to replace line 4 in the file with "Its just a test"
$contents[3] = "Its just a test";

then write the array back to the file

all the brothers were valiant!

[br][br]The truely intelligent people are not those who create the dots; rather they are they ones with the ability to connect the dots into a coherent picture

#5 dual_alliance

dual_alliance
  • Members
  • PipPipPip
  • Advanced Member
  • 140 posts
  • LocationNSW, Australia

Posted 10 August 2006 - 05:03 PM

Thanks for your help litebearer ;D




0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users