PHP从文件读取和写入JSON [英] PHP read and write JSON from file
问题描述
我在文件list.txt
中具有以下JSON:
I have the following JSON in a file list.txt
:
{
"bgates":{"first":"Bill","last":"Gates"},
"sjobs":{"first":"Steve","last":"Jobs"}
}
如何使用PHP将"bross":{"first":"Bob","last":"Ross"}
添加到文件中?
How do I add "bross":{"first":"Bob","last":"Ross"}
to my file using PHP?
这是我到目前为止所拥有的:
Here's what I have so far:
<?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类型的对象用作数组:
Which gives me a Fatal error: Cannot use object of type stdClass as array on this line:
$json[$user] = array("first" => $first, "last" => $last);
我正在使用PHP5.2.有什么想法吗?谢谢!
I'm using PHP5.2. Any thoughts? Thanks!
推荐答案
The clue is in the error message - if you look at the documentation for json_decode
note that it can take a second param, which controls whether it returns an array or an object - it defaults to object.
因此将您的呼叫更改为
$json = json_decode(file_get_contents($file), true);
它将返回一个关联数组,您的代码应该可以正常工作.
And it'll return an associative array and your code should work fine.
这篇关于PHP从文件读取和写入JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!