为了账号安全,请及时绑定邮箱和手机立即绑定

修改后无法从JSON文件中获取数据

修改后无法从JSON文件中获取数据

PHP
千巷猫影 2021-11-26 19:17:28
我创建了一个类,负责获取和修改 JSON 文件中的数据。使用添加数据的方法后,获取数据的方法返回null。JSON 表示一个具有两个字段的对象:“最后一个 id” - 数字和“posts” - 帖子数组(包含字符串的关联数组)。方法“getPosts()”必须返回帖子数组,方法“addPost($post)”必须向数组添加一个新帖子。问题出现在这个场景中:我使用 getPosts(),它工作得很好。我使用 addPost(),它将新帖子添加到 JSON。如果之后我再次使用 getPosts() 它将返回 null。如果我在不使用 addPost() 的情况下再次运行脚本,getPosts() 将返回一个更新的数组。为什么 addPost() 会影响 getPosts() 的结果?class PostStorage {    private $path;    public function __construct($path) {        $this->path = $path;        if (file_exists($path)) return;        $contents = array(            "last_id" => 0,            "posts" => array()        );        $this->setStorage($contents);    }    public function getPosts() {        return $this->getStorage()['posts'];    }    public function addPost($post) {        $storage = $this->getStorage();        $newId = $storage['last_id'] + 1;        $post['id'] = $newId;        $storage['posts'][] = $post;        $storage['last_id'] = $newId;        $this->setStorage($storage);    }    private function setStorage($contents) {        $handler = fopen($this->path, 'w');        fwrite($handler, json_encode($contents));        fclose($handler);    }    private function getStorage() {        $handler = fopen($this->path, 'r');        $contents = fread($handler, filesize($this->path));        fclose($handler);        return json_decode($contents, TRUE);    }}$postStorage = new PostStorage(JSON_PATH);$post = array(    "title" => "some title",    "content" => "some content");echo(json_encode($postStorage->getPosts())); // is fine$postStorage->addPost($post); // file was modifiedecho(json_encode($postStorage->getPosts())); // now it returns null
查看完整描述

1 回答

?
慕桂英3389331

TA贡献2036条经验 获得超8个赞

调用的结果filesize被缓存。因此,第二次调用filesizeingetStorage返回旧大小。因此,仅返回文件的一部分:{"last_id":1,"posts":[{。这会导致 json 解析器失败并返回一个空数组。这个数组没有posts键,因此在getPosts.


解决办法是先调用clearstatcache();再调用filesize。示例代码:


  private function getStorage() {

        clearstatcache();

        $handler = fopen($this->path, 'r');

        $contents = fread($handler, filesize($this->path));

        fclose($handler);


        return json_decode($contents, TRUE);

    }

有关此缓存“功能”的更多信息:https : //www.php.net/manual/en/function.clearstatcache.php


查看完整回答
反对 回复 2021-11-26
  • 1 回答
  • 0 关注
  • 242 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信