1

Мне нужно прочитать файл, разобрать его на массив, дописать строку и записать снова json. Как правильно это сделать?

Я пробую так, но ничего не выходит:

$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"}}

Как правильно это сделать?

1 ответ 1

3

Вот так попробуйте :)

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

В вашем примере, arr всегда пустой при наличии данных из файла.

2
  • Спасибо, добрый человек! )
    – VINET
    4 авг 2016 в 22:46
  • Немного исправил код, добавил функцию file_exists, а то у Вас там стоял isset, который всегда по сути будет true возвращать в коде.
    – Firepro
    4 авг 2016 в 22:49

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.