php file_put_contents ...我不能在开头追加?

时间:2010-12-16 11:50:30

标签: php file-get-contents

<?php
$file = 'people.txt';
// The new person to add to the file
$person = "John Smith\n";
// Write the contents to the file, 
// using the FILE_APPEND flag to append the content to the end of the file
// and the LOCK_EX flag to prevent anyone else writing to the file at the same time
 file_put_contents($file, $person, FILE_APPEND | LOCK_EX);
?>

这会将内容附加到文件末尾。我想在文件的开头写最新的。

4 个答案:

答案 0 :(得分:4)

the manual page所示,没有标记可以预先添加数据。

您需要先使用file_get_contents()读取整个文件,然后添加值,并保存整个字符串。

答案 1 :(得分:1)

如果你想使用file_put_contents,你将无法选择,你需要阅读/连续/写。

<?
$file = 'people.txt';  
$appendBefore = 'Go to the beach';
$temp = file_get_contents($file);
$content = $appendBefore.$temp;
file_put_contents($file, $content);

答案 2 :(得分:0)

在文件开头写入可能会在文件系统和硬盘上产生一些不必要的开销。

作为解决方案,您必须在内存中读取整个文件,编写要添加的新内容,然后编写旧内容。这需要大型文件的时间和内存(这取决于您拥有的实际工作负载,但作为一般规则,它很慢)。

正常追加(最后)然后向后读取文件是否可行?这将导致更快的写入,但读取速度更慢。它主要取决于你的工作量:)

答案 3 :(得分:0)

在几乎相同的问题中查看this answer

你可能不想使用它,因为看起来你只使用一个小文件。