Domanda

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

When i recieve 10 requests to this php script a file is created as in the below format

{"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. When i tried to validate the above generated json text in http://jsonlint.com/

i get the Error message Expecting 'EOF', '}', ',', ']'

Q2. How do i achieve the below format

[
{"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 ?

È stato utile?

Soluzione

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

Altri suggerimenti

Try:

$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);
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top