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 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 exit you need to get:

 {"1":{"name":"name","email":"email1"}, "2":{"name":"name","email":"email1"}} 

How to do it right?

    1 answer 1

    So try :)

     $filename = 'json.txt'; $name = "name"; $email = "email"; $arr = array(); if (file_exists($filename)) { $file = file_get_contents('json.txt', true); $arr = json_decode($file ,true); } $arr[count($arr)+1]["name"] = $name; $arr[count($arr)]["email"] = $email; echo json_encode($arr); $decode = json_decode($file ,true); $fp = fopen($filename, "w"); fwrite($fp, json_encode($arr)); fclose ($fp); 

    In your example, arr is always empty if there is data from the file.

    • Thank you, kind man! ) - VINET
    • I corrected the code a bit, added the file_exists function, otherwise you have an isset standing there, which in fact will always return true in code. - Firepro