php json_encode到一个文件,格式问题

时间:2014-02-01 00:01:47

标签: php json jslint

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

$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/

中验证上面生成的json文本时

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

Q2。我如何实现以下格式

[
{"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"}
]

每个新条目都需要附加逗号以及结尾] 框?

2 个答案:

答案 0 :(得分:2)

您需要读取文件并将其解码为数组,附加到该数组,然后将整个数组写出来。

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

答案 1 :(得分:0)

尝试:

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

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

$file = file_get_contents('some_file');
$file = json_decode($file);

$file[] = $jsoninfo;
$data = json_encode($file, JSON_FORCE_OBJECT);

file_put_contents('somefile', $data);