第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決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條經(jīng)驗 獲得超6個贊

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


$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(). 然后我們獲取現(xiàn)有文件內(nèi)容并將其連接到您的字符串,并覆蓋文件。


編輯: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);

編輯:創(chuàng)建單線的功能


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 關注
  • 265 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網(wǎng)微信公眾號