M
M
Millerish2016-08-05 01:01:20
PHP
Millerish, 2016-08-05 01:01:20

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

At the output you need to get:
{"1":{"name":"name","email":"email1"}, "2":{"name":"name","email":"email1"}}

How right?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Andrey, 2016-08-05
@a_ovchinnikov

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

You created an empty array, but you should have initialized it with data from a file. Also, the echo construct is useless here, unless of course you use it for test purposes.
By the way, another life hack - inserting a value at the end of an array can be made a little easier:
$arr[] = [
    'name' => $name,
    'email' => $email
];

The [] operator allows you to put a value at the end of an array. In this case, we put an associative array.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question