PHP 从文件读取和写入 JSON

2022-08-30 10:35:02

我在一个文件中有以下JSON:list.txt

{
"bgates":{"first":"Bill","last":"Gates"},
"sjobs":{"first":"Steve","last":"Jobs"}
}

如何使用 PHP 添加到我的文件?"bross":{"first":"Bob","last":"Ross"}

以下是我到目前为止所拥有的:

<?php

$user = "bross";
$first = "Bob";
$last = "Ross";

$file = "list.txt";

$json = json_decode(file_get_contents($file));

$json[$user] = array("first" => $first, "last" => $last);

file_put_contents($file, json_encode($json));

?>

这给了我一个致命的错误:无法在此行上使用stdClass类型的对象作为数组:

$json[$user] = array("first" => $first, "last" => $last);

我使用的是 PHP5.2。有什么想法吗?谢谢!


答案 1

线索在错误消息中 - 如果您查看文档以获取json_decode请注意,它可以采用第二个参数,该参数控制它是返回数组还是对象 - 它默认为object。

因此,请将您的呼叫更改为

$json = json_decode(file_get_contents($file), true);

它将返回一个关联数组,您的代码应该可以正常工作。


答案 2

在 PHP 中读取和写入 JSON 的示例:

$json = json_decode(file_get_contents($file),TRUE);

$json[$user] = array("first" => $first, "last" => $last);

file_put_contents($file, json_encode($json));

推荐