tags:

views:

83

answers:

2

I'm writing some code and I need to write a number to a specific line. Here's what I have so far:

<?php

$statsloc = getcwd() . "/stats/stats.txt";
$handle = fopen($statsloc, 'r+');

for($linei = 0; $linei < $zone; $linei++) $line = fgets($handle);
$line = trim($line);
echo $line;

$line++;
echo $line;

I don't know where to continue after this. I need to write $line to that line, while maintaining all the other lines.

+2  A: 

This should work. It will get rather inefficient if the file is too large though, so it depends on your situation if this is a good answer or not.

$stats = file('/path/to/stats', FILE_IGNORE_NEW_LINES);   // read file into array
$line = $stats[$offset];   // read line
array_splice($stats, $offset, 0, $newline);    // insert $newline at $offset
file_put_contents('/path/to/stats', join("\n", $stats));    // write to file
deceze
I'm not sure how this fits in with the code I already have. Can you help me out? Please?
I'm sorry, this piece is pretty self-explanatory, you'll have to give it a try yourself.
deceze
+2  A: 

you can use file to get the file as an array of lines, then change the line you need, and rewrite the whole lot back to the file.

<?php
$filename = getcwd() . "/stats/stats.txt";
$line_i_am_looking_for = 123;
$lines = file( $filename , FILE_IGNORE_NEW_LINES );
$lines[$line_i_am_looking_for] = 'my modified line';
file_put_contents( $filename , implode( "\n", $lines ) );
nathan
I've assumed you need to modify a line, not inject a new one - if you need to inject a new one see deceze's answer - as for the difference between join and implode, there is none, join is an alias of implode.
nathan
I've snatched `FILE_IGNORE_NEW_LINES` from your answer, good thinking to include it. :)
deceze
@deceze most welcome, no problem and good idea
nathan