写入PHP中的特定行 [英] Write to specific line in PHP

查看:60
本文介绍了写入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;

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

解决方案

您可以使用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 ) );

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.

解决方案

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 ) );

这篇关于写入PHP中的特定行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆