首页 > 解决方案 > PHP 更新文件中的值

问题描述

我有一个 PHP 脚本和一个文件。该文件仅包含“8”。我需要使用 PHP 脚本将此值更新为“9”(或任何值,只需将文件中的内容加 1)。

目前我有一个看起来像这样的文件:

<?php
file_put_contents("numberFile", file_get_contents("numberFile")[0]++);
?>

这应该将它从第一行 + 1 读取的内容写入文件。但是它不起作用。有一个更好的方法吗?

标签: phpfile-handling

解决方案


$content = file_get_contents('numberFile');
if (isset($content))
{
    $number = intval($content);
    file_put_contents('numberFile', ++$number);
}

未经测试,但我怀疑这很接近你想要的东西,如果不完全一样的话。:)

正如评论中所述,不要试图在一行中完成所有操作,分解代码以便其可读。


推荐阅读