在 php 中读取然后覆盖文件内容的最有效方法是什么?
What's the most efficient way to read from and then overwrite file contents in php?
我想将一个文件读入一个字符串,修改内容并将处理后的字符串写回到文件中。
此外,对服务器的另一个请求可能启动得太早,并尝试在第一个请求通过之前写入相同的文件——这绝不能发生(到目前为止我正在使用 flock)——如果脚本会阻塞直到锁定已释放。
这是某种不完整的方法
$h = fopen($fp, 'a+');
flock($h, LOCK_EX);
$oTxt = '';
while (!feof($file)) {
$oTxt .= fread($h, 8192);
}
rewind($h);
ftruncate($h, 0)
fwrite($h, ); // process contents and write it back
flock($h, LOCK_UN);
fclose($h);
注意:这个问题与 What's the best way to read from and then overwrite file contents in php? 非常相似(在我的例子中它是一个 json 文件,我想解码、插入或编辑一些节点,然后再次编码)但它不是重复。
您可以将 while
循环替换为对 stream_get_contents
的单个调用。并且你应该使用模式 r+
来读写文件; a+
将在您开始时将流定位在文件末尾,因此不会有任何内容可读。
$h = fopen($fp, 'r+');
flock($h, LOCK_EX);
$oTxt = stream_get_contents($h);
// Process contents
rewind($h);
ftruncate($h, 0);
fwrite($h, $oTxt);
flock($h, LOCK_UN);
fclose($h);
我想将一个文件读入一个字符串,修改内容并将处理后的字符串写回到文件中。 此外,对服务器的另一个请求可能启动得太早,并尝试在第一个请求通过之前写入相同的文件——这绝不能发生(到目前为止我正在使用 flock)——如果脚本会阻塞直到锁定已释放。
这是某种不完整的方法
$h = fopen($fp, 'a+');
flock($h, LOCK_EX);
$oTxt = '';
while (!feof($file)) {
$oTxt .= fread($h, 8192);
}
rewind($h);
ftruncate($h, 0)
fwrite($h, ); // process contents and write it back
flock($h, LOCK_UN);
fclose($h);
注意:这个问题与 What's the best way to read from and then overwrite file contents in php? 非常相似(在我的例子中它是一个 json 文件,我想解码、插入或编辑一些节点,然后再次编码)但它不是重复。
您可以将 while
循环替换为对 stream_get_contents
的单个调用。并且你应该使用模式 r+
来读写文件; a+
将在您开始时将流定位在文件末尾,因此不会有任何内容可读。
$h = fopen($fp, 'r+');
flock($h, LOCK_EX);
$oTxt = stream_get_contents($h);
// Process contents
rewind($h);
ftruncate($h, 0);
fwrite($h, $oTxt);
flock($h, LOCK_UN);
fclose($h);