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!';
}
- 1 回答
- 0 關注
- 265 瀏覽
添加回答
舉報