php jsonencode到文件,格式问题 [英] php jsonencode to a file , format issue

查看:60
本文介绍了php jsonencode到文件,格式问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用php从发布的输入中创建一个json编码的文件

I am trying to create a json encoded file using php from the posted inputs

$name =$_POST['n'];
$age = $_POST['a'];
$occ= $_POST['n'];
$country = $_POST['n'];

$jsoninfo = array('name'=>$name,'age'=>$age,
                 'occupation'=>$occ,'country'=>$country);
$generated_json =  json_encode($jsoninfo);

echo $generated_json;

file_put_contents('somefile', $generated_json, FILE_APPEND );

当我收到10个对此php脚本的请求时,将按照以下格式创建文件

{"name":"steve","age":"40","occupation":"ceo","country":"us"}
{"name":"steve","age":"40","occupation":"ceo","country":"us"}
{"name":"steve","age":"40","occupation":"ceo","country":"us"}
{"name":"steve","age":"40","occupation":"ceo","country":"us"}

Q1.当我尝试在 http://jsonlint.com/

我收到错误消息 Expecting 'EOF', '}', ',', ']'

第二季度.我如何实现以下格式

[
{"name":"steve","age":"40","occupation":"ceo","country":"us"},
{"name":"steve","age":"40","occupation":"ceo","country":"us"},
{"name":"steve","age":"40","occupation":"ceo","country":"us"},
{"name":"steve","age":"40","occupation":"ceo","country":"us"}
]

每个新条目都必须附加逗号和结尾的] 框?

The comma , and also the ending ] box need to be appended for every new entry ?

推荐答案

您需要读取文件并将其解码为一个数组,追加到该数组中,然后将整个数组写出.

You need to read the file and decode it into an array, append to that array, and then write the whole array out.

$name =$_POST['n'];
$age = $_POST['a'];
$occ= $_POST['n'];
$country = $_POST['n'];

$old_contents = file_get_contents('somefile');
$jsoninfo = $old_contents ? json_decode($old_contents) : array();
$jsoninfo[] = array('name'=>$name,'age'=>$age,
                    'occupation'=>$occ,'country'=>$country);
$generated_json =  json_encode($jsoninfo);

echo $generated_json;

file_put_contents('somefile', $generated_json);

这篇关于php jsonencode到文件,格式问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆