Answer the question
In order to leave comments, you need to log in
PHP how to work with JSON correctly?
Good evening!
I need to read the file, parse it into an array, add a line and write json again. How to do it right?
I try like this, but it doesn't work:
$file = file_get_contents('json.txt', true);
$name = "name";
$email = "email";
if(isset($file)){
$arr = array();
}
$arr[count($arr)+1]["name"] = $name;
$arr[count($arr)]["email"] = $email;
echo json_encode($arr);
$decode = json_decode($file ,true);
$fp = fopen("json.txt", "w");
fwrite($fp, json_encode($arr) );
fclose ($fp);
{"1":{"name":"name","email":"email1"}, "2":{"name":"name","email":"email1"}}
Answer the question
In order to leave comments, you need to log in
The point is that now you just write the contents of the $arr variable to the file, which will always be the same, regardless of the contents of the file:
The correct algorithm is as follows:
1. Get the contents of the file;
2. Using the json_decode function, we made an associative array from the content;
3. Added new data to the end of this array;
4. Using the json_encode function, we again received a JSON string from the array;
5. Write the result to a file.
In general, the structure of your code is very similar to what I described. Probably the error is here:
if(isset($file)){
$arr = array();
}
$arr[count($arr)+1]["name"] = $name;
$arr[count($arr)]["email"] = $email;
echo json_encode($arr);
$arr[] = [
'name' => $name,
'email' => $email
];
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question