DBlaics DBlaics - 25 days ago 6
JSON Question

how to save data in json with php

I have a json file

users.json


{
"Jessica Smith": {
"name": "Jessica",
"surname": "Smith",
"email": "jessica.smith@alias.com",
"pass": "jessicasmith",
"sex": "female"
},
"Jessica Smith2": {
"name": "Jessica",
"surname": "Smith2",
"email": "jessica.smith2@alias.com",
"pass": "jessicasmith2",
"sex": "female"
},
}


PHP code

$file = fopen("users.json", a);
if(!$file) die ( "Error");
$value = "given_name:".$name."\nfamily_name:".$surname."\nemail:".$email."\npass:".$psw."\nsex: ".$type."\n";
fwrite($file, $value);
fclose($file);


With this code I only add string
$value
after the last line,
there is a method where I can convert
$value
in json form??
I try to use
json_encode
.

string json_encode(mixed $add[$value]);


but it doesn't work.

For example, i want add Jessica Smith3 in
users.json


"Jessica Smith3": {
"name": "Jessica",
"surname": "Smith3",
"email": "jessica.smith3@alias.com",
"pass": "jessicasmith3",
"sex": "female"
},

Answer

Your $value is not valid JSON and the file manipulation produces an invalid JSON file. You should use

$value =  array(  "given_name"=>$name,
                  "family_name"=>$surname,
                  "email"=>$email,
                  "pass"=>$psw,
                  "sex"=>type);
$file = fopen("users.json", a);
if(!$file) die ( "Error");
$f = json_decode( $file );
$f[] = $value;
$file = json_encode( $f );
fwrite($file, $value);
fclose($file);