Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Write to specific line in PHP

Tags:

php

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.

like image 724
Robert Avatar asked Jul 19 '10 01:07

Robert


3 Answers

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 ) );
like image 194
nathan Avatar answered Oct 29 '22 03:10

nathan


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
like image 42
deceze Avatar answered Oct 29 '22 02:10

deceze


I encountered this today and wanted to solve using the 2 answers posted but that didn't work. I had to change it to this:

<?php
$filepathname = "./stats.txt";
$target = "1234";
$newline = "after 1234";

$stats = file($filepathname, FILE_IGNORE_NEW_LINES);   
$offset = array_search($target,$stats) +1;
array_splice($stats, $offset, 0, $newline);   
file_put_contents($filepathname, join("\n", $stats));   
?>

Because these lines don't work since the arg of the array is not an index:

$line = $stats[$offset]; 
$lines[$line_i_am_looking_for] = 'my modified line';

Had to add that +1 to have the new line under the searched text.

like image 20
quinestor Avatar answered Oct 29 '22 01:10

quinestor