Php 用新的Json数据覆盖Json文件
因此,我将这个json文件(json.json)存储在服务器上,每次调用这个php类时,我都想用新的json数据(“refresh_token”对象)覆盖它:Php 用新的Json数据覆盖Json文件,php,json,Php,Json,因此,我将这个json文件(json.json)存储在服务器上,每次调用这个php类时,我都想用新的json数据(“refresh_token”对象)覆盖它: $file = file_get_contents('/var/json.json'); $json = json_decode($file); **$REFRESH_TOKEN** = $json->refresh_token; $json = file_get_contents("https:/
$file = file_get_contents('/var/json.json');
$json = json_decode($file);
**$REFRESH_TOKEN** = $json->refresh_token;
$json = file_get_contents("https://xxxxxxxxxxx&refresh_token=**$REFRESH_TOKEN**");
$obj = json_decode($json, true);
$AccessToken = $obj->access_token;
$RefreshToken = $obj->refresh_token;
**file_put_contents('/var/json.json', json_encode($RefreshToken));**
json文件如下所示:
{"token_type":"bearer",
"expires_in":3600,
"scope":"xxxxxxx",
"access_token":"xxxx",
**"refresh_token":"xxxxx",**
"user_id":"xxxxxx"}
我反复出现错误:每当我第二次调用该类时,都试图在
中获取非对象的属性。第一次调用后,我查看了json文件的内部,发现它没有包含任何内容。这表明文件内容('/var/json.json',json\u encode($refreshttoken))
不起作用
有谁能给我一个提示,说明我做错了什么 确保您有权限写入该文件。将文件权限更改为777。从您的代码中,不清楚您要做什么。我猜是这样的:
- 从文件中获取json对象
- 修改刷新令牌
- 将json对象写回文件
$REFRESHTOKEN = $_GET['REFRESH_TOKEN']; // Calculate refresh token
$json = json_decode(file_get_contents('/var/json.json')); // fetch json object from file
$json->refresh_token = $REFRESHTOKEN // modify refresh token
file_put_contents('/var/json.json', json_encode($json)); // write json object back to file
您所做的只是将刷新令牌写入文件,而不是整个对象。这就是为什么在第二次尝试时,对象不在那里…如果将
json\u decode
的第二个参数设置为true
,则会得到关联数组而不是对象
json\u解码的文档
:是的,这就是我要做的。从json文件中获取刷新\u标记,对其进行修改,然后用新的刷新\u标记覆盖旧的刷新\u标记并返回到json文件中。代码中的第一行完成了什么?它从某处获取刷新令牌,因为我不明白您希望从代码中的何处获取刷新令牌。已解决@Alexander,关于只将refresh_令牌写入json文件,您是对的。我将所有json对象作为参数放在file_put_contents方法中,它的工作方式与chamr类似。我仍然不明白为什么我不只是将刷新令牌编码到json文件中。因为在json\u encode($refreshttoken)
中,变量只包含令牌。