亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

用PHP編寫TXT文件,想在開頭插入新行

用PHP編寫TXT文件,想在開頭插入新行

PHP
阿晨1998 2022-07-29 10:10:18
是否可以在 .txt 文件的開頭插入新行?我了解到 usingfwrite(filename, sentence)是在末尾添加一個新行。但我想知道是否有任何方法可以在開頭添加新行,就像我原來的 .txt 文件是AAA當我添加一個新行“BBB”時,它看起來像BBB AAA
查看完整描述

1 回答

?
墨色風雨

TA貢獻1853條經驗 獲得超6個贊

您可以file_get_contents()先使用獲取原始數據,然后將字符串添加到該數據之前:


$existing = file_get_contents('/path/to/file.txt');

$fp = fopen('/path/to/file.txt', 'w');    


$myString = 'hello world'. PHP_EOL;


fwrite($fp, $myString. $existing);

fclose($fp);

在這里,我們用 - 打開文件w以完全覆蓋,而不是追加。因此,我們需要在fopen(). 然后我們獲取現有文件內容并將其連接到您的字符串,并覆蓋文件。


編輯:file_put_contents() - 正如 Nigel Ren 所建議的那樣


$existing = file_get_contents('/path/to/file.txt');

$myString = 'hello world'. PHP_EOL;


file_put_contents('/path/to/file.txt', $myString. $existing);

編輯:創建單線的功能


function prepend_to_file(string $file, string $data)

{

    if (file_exists($file)) {

        try {

            file_put_contents($file, $data. file_get_contents($file));


            return true;

        } catch (Exception $e) {

            throw new Exception($file. ' couldn\'t be amended, see error: '. $e->getMessage());

        }

    } else {

        throw new Exception($file. ' wasn\'t found. Ensure it exists');

    }

}


# then use:

if (prepend_to_file('/path/to/file.txt', 'hello world')) {

    echo 'prepended!';

}


查看完整回答
反對 回復 2022-07-29
  • 1 回答
  • 0 關注
  • 272 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號