写入PHP中的特定行

Rob*_*ert 6 php

我正在写一些代码,我需要在特定的行上写一个数字.这是我到目前为止所拥有的:

<?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;
Run Code Online (Sandbox Code Playgroud)

在此之后我不知道该在哪里继续.我需要在该行写入$ line,同时保留所有其他行.

nat*_*han 16

您可以使用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 ) );
Run Code Online (Sandbox Code Playgroud)


dec*_*eze 6

这应该有效。如果文件太大,它会变得相当低效,所以这取决于你的情况,这是否是一个好的答案。

$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
Run Code Online (Sandbox Code Playgroud)