我有一个json文件
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代码
$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);
使用此代码我只在最后一行之后添加字符串$value
,
有一种方法可以用json格式转换$value
吗?
我尝试使用json_encode
。
string json_encode(mixed $add[$value]);
但它不起作用。
例如,我想在users.json
"Jessica Smith3": {
"name": "Jessica",
"surname": "Smith3",
"email": "jessica.smith3@alias.com",
"pass": "jessicasmith3",
"sex": "female"
},
答案 0 :(得分:1)
您的$ value无效JSON,文件操作会生成无效的JSON文件。 你应该使用
$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);