php - 这是获取和删除文件第一行的最有效方法吗?

标签 php file

我有一个脚本,每次调用它时,都会获取文件的第一行。已知每一行的长度完全相同(32 个字母数字字符)并以“\r\n”结尾。 获取第一行后,脚本将其删除。

这是通过这种方式完成的:

$contents = file_get_contents($file));
$first_line = substr($contents, 0, 32);
file_put_contents($file, substr($contents, 32 + 2)); //+2 because we remove also the \r\n

显然它有效,但我想知道是否有更聪明(或更有效)的方法来做到这一点?

在我的简单解决方案中,我基本上读取并重写整个文件,只是为了获取和删除第一行

最佳答案

我昨天想到了这个想法:

function read_and_delete_first_line($filename) {
  $file = file($filename);
  $output = $file[0];
  unset($file[0]);
  file_put_contents($filename, $file);
  return $output;
}

关于php - 这是获取和删除文件第一行的最有效方法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2404707/

相关文章:

php - 在 linux 服务器上调用非对象的成员函数 fetch_assoc() 但在 windows 上不调用

php - Woocommerce - 支付完成后调用自定义函数

php - 如何使用 php、graph API 通过 id 删除 facebook 中的帖子

php - 从数组生成 jquery 列表

php - 计算目录PHP中有多少文件

python - 如何根据代码的输出在 jupyter 笔记本中创建文本文件

php - CodeIgniter - 表单验证和 POST 数据

android - 如何访问手机或SD卡内存中的文件

c - C 中的重复消除

.net - SSD 驱动器上奇怪的目录删除行为