0

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 ?

2 Answers 2

2

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);
Sign up to request clarification or add additional context in comments.

2 Comments

Yes that worked, Is there Any shortcut process other than decoding the file again ??
There are shortcuts you could take, but I wouldn't recommend it. If you're doing this with a large file, you should consider a different design entirely, such as a database.
0

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

2 Comments

Don't use FILE_APPEND when you're replacing the whole array.
Good spot, missed that!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.