在PHP中,如果您写入文件,它将写入该现有文件的结尾.
我们如何在该文件的开头添加要写入的文件?
我已尝试过rewind($handle)功能,但如果当前内容大于现有内容,则会覆盖.
有任何想法吗?
ale*_*lex 23
$prepend = 'prepend me please';
$file = '/path/to/file';
$fileContents = file_get_contents($file);
file_put_contents($file, $prepend . $fileContents);
Run Code Online (Sandbox Code Playgroud)
Fra*_*til 14
file_get_contents解决方案对于大文件效率低下.此解决方案可能需要更长时间,具体取决于需要预先添加的数据量(实际上更好),但它不会占用内存.
<?php
$cache_new = "Prepend this"; // this gets prepended
$file = "file.dat"; // the file to which $cache_new gets prepended
$handle = fopen($file, "r+");
$len = strlen($cache_new);
$final_len = filesize($file) + $len;
$cache_old = fread($handle, $len);
rewind($handle);
$i = 1;
while (ftell($handle) < $final_len) {
fwrite($handle, $cache_new);
$cache_new = $cache_old;
$cache_old = fread($handle, $len);
fseek($handle, $i * $len);
$i++;
}
?>
Run Code Online (Sandbox Code Playgroud)
$filename = "log.txt";
$file_to_read = @fopen($filename, "r");
$old_text = @fread($file_to_read, 1024); // max 1024
@fclose($file_to_read);
$file_to_write = fopen($filename, "w");
fwrite($file_to_write, "new text".$old_text);
Run Code Online (Sandbox Code Playgroud)