簡體   English   中英

PHP:在文件的特定行之間插入內容?

[英]PHP : Insert content in between specific line of a file?

想象一下,我有一個包含以下內容的TXT文件(some.txt):

data of first line
data of next line
#start-marker

data of next line
#end-marker
data of next line

我想在#start-marker之后寫幾行

目前,我有這個:

$fp = fopen('some.txt','r+');
$insertPos=0;
while (!feof($fp)) {
    $line=fgets($fp);
    if (strpos($line, '#start-marker')!==false) {
        $insertPos=ftell($fp);
}
fseek($fp,$insertPos);
fwrite($fp,'Data to be written');
fclose($fp);

但是,問題是:

data of first line
data of next line
#start-marker
Data to be written

新插入的行之后所有行均消失。

這個怎么做 ?

預期產量:

data of first line
data of next line
#start-marker

Data to be written
data of next line
#end-marker
data of next line
$myfile = file_get_contents('some.txt');
$insert = '#start-marker blah blah blah new data here';
$myfile = str_replace('#start-marker', $insert, $myfile, 1);
file_put_contents('some.txt', $myfile);

我認為您正在尋找追加到文件。 嘗試從“ r +”更改為向代碼添加a+模式:

$fp = fopen('some.txt','a+');
$insertPos=0;
while (!feof($fp)) {
    $line=fgets($fp);
    if (strpos($line, '#start-marker')!==false) {
        $insertPos=ftell($fp);
}
fseek($fp,$insertPos);
fwrite($fp,'Data to be written');
fclose($fp);

參考:模式參數-http : //php.net/manual/zh/function.fopen.php

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM