php 文件写入json,PHP从文件读取和写入JSON

PHP从文件读取和写入JSON

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

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

这给了我一个致命的错误:不能使用stdClasstypes的对象作为这一行上的数组:

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

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

线索是在错误信息中 – 如果你看看json_decode的文档,注意它可能需要第二个参数,它控制它是否返回一个数组或对象 – 它默认是object。

所以改变你的电话

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

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

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

$json = json_decode(file_get_contents($file),TRUE); $json[$user] = array("first" => $first, "last" => $last); file_put_contents($file, json_encode($json));

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

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

这是如何返回没有第二个参数(作为stdClass的一个实例)。

你需要通过传递true参数来使解码函数返回一个数组。

json_decode(file_get_contents($file),true);

尝试使用json_decode函数的第二个参数:

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

这应该为你获得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);

如果您想要在定义良好的合成器中显示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"; }

当你想创buildJSON格式时,必须使用以下格式来读取:

[ { "":"", "":[ { "":"", "":"" } ] } ]

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值