PHP从fi读取和写入JSON
我在文件list.txt中具有以下JSON:
{
"bgates":{"first":"Bill","last":"Gates"},
"sjobs":{"first":"Steve","last":"Jobs"}
}
如何使用PHP将"bross":{"first":"Bob","last":"Ross"}添加到我的文件中?
这是我到目前为止的内容:
$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。 有什么想法吗? 谢谢!
Josiah asked 2020-07-20T17:25:39Z
8个解决方案
81 votes
错误消息中的线索是-如果您查看json_decode的文档,请注意,它可以采用第二个参数,该参数控制返回数组还是对象-默认为对象。
因此,将您的通话更改为
$json = json_decode(file_get_contents($file), true);
并且它将返回一个关联数组,您的代码应该可以正常工作。
John Carter answered 2020-07-20T17:26:09Z
22 votes
在PHP中读写JSON的示例:
$json = json_decode(file_get_contents($file),TRUE);
$json[$user] = array("first" => $first, "last" => $last);
file_put_contents($file, json_encode($json));
4EACH answered 2020-07-20T17:26:29Z
8 votes
或者只是将$ json用作对象:
$json->$user = array("first" => $first, "last" => $last);
这是不使用第二个参数(作为stdClass的实例)而返回的方式。
Liam Bailey answered 2020-07-20T17:26:54Z
7 votes
您需要通过传递json_decode(file_get_contents($file),true);参数来使解码函数返回一个数组。
json_decode(file_get_contents($file),true);
Aknosis answered 2020-07-20T17:27:14Z
3 votes
尝试对json_decode函数使用第二个参数:
$json = json_decode(file_get_contents($file), true);
Lubor Bílek answered 2020-07-20T17:27:34Z
3 votes
这应该为您工作以获取list.txt文件的内容
$headers = array('http'=>array('method'=>'GET','header'=>'Content: type=application/json \r\n'.'$agent \r\n'.'$hash'));
$context=stream_context_create($headers);
$str = file_get_contents("list.txt",FILE_USE_INCLUDE_PATH,$context);
$str=utf8_encode($str);
$str=json_decode($str,true);
print_r($str);
Ur Friend answered 2020-07-20T17:27:54Z
2 votes
如果要以定义良好的格式显示JSON数据,可以将代码修改为:
file_put_contents($file, json_encode($json,TRUE));
$headers = array('http'=>array('method'=>'GET','header'=>'Content: type=application/json \r\n'.'$agent \r\n'.'$hash'));
$context=stream_context_create($headers);
$str = file_get_contents("list.txt",FILE_USE_INCLUDE_PATH,$context);
$str1=utf8_encode($str);
$str1=json_decode($str1,true);
foreach($str1 as $key=>$value)
{
echo "key is: $key.\n";
echo "values are: \t";
foreach ($value as $k) {
echo " $k. \t";
# code...
}
echo "
";
echo "\n";
}
Kevin Guan answered 2020-07-20T17:28:14Z
1 votes
当您要创建json格式时,必须采用以下格式才能读取:
[
{
"":"",
"":[
{
"":"",
"":""
}
]
}
]
markllibre answered 2020-07-20T17:28:34Z