PHP从文件中读写JSON

Jos*_*iah 44 php json

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

{
"bgates":{"first":"Bill","last":"Gates"},
"sjobs":{"first":"Steve","last":"Jobs"}
}
Run Code Online (Sandbox Code Playgroud)

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

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

<?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));

?>
Run Code Online (Sandbox Code Playgroud)

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

$json[$user] = array("first" => $first, "last" => $last);
Run Code Online (Sandbox Code Playgroud)

我正在使用PHP5.2.有什么想法吗?谢谢!

Joh*_*ter 81

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

所以改变你的电话

$json = json_decode(file_get_contents($file), true);
Run Code Online (Sandbox Code Playgroud)

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

  • 我讨厌`json_decode`默认返回一个类而不是一个数组.每次我在一个月内第一次使用`json_decode`时,这就让我兴奋不已. (5认同)

4EA*_*ACH 22

用于在PHP中读写JSON的示例:

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

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

file_put_contents($file, json_encode($json));
Run Code Online (Sandbox Code Playgroud)

  • json_encode的第二个参数不是布尔值,所以编写`json_encode($ json,TRUE)`是错误的. (2认同)

Lia*_*ley 8

或者只使用$ json作为对象:

$json->$user = array("first" => $first, "last" => $last);
Run Code Online (Sandbox Code Playgroud)

这是没有第二个参数(作为stdClass的实例)返回的方式.


Akn*_*sis 7

您需要通过传入true参数使decode函数返回一个数组.

json_decode(file_get_contents($file),true);