Add information to a .json file

0

Can you add information with a different reference in a json file with php?

Type:

file.json

{ 
     'id': 'rt6hj7'{
          'nome':'Miguel'
      },
      'id': 'rt10hg9'{
          'nome':'Sagas'
      } 
}

And add José with the id: 8dhus8763 and do not subscribe any information already contained in the file. Make file.json a kind of database.

Does anyone have an idea?

Thank you for your help

    
asked by anonymous 28.01.2016 / 17:04

1 answer

0

Yes, it is possible, however, first to note that your JSON structure is invalid, this does not make sense 'id': 'rt6hj7'{ so you should start by using a valid JSON, eg

{
   "rt6hj7": {
        "nome": "Miguel"
    },
    "rt10hg9": {
        "nome": "Sagas"
    }
}

Now assuming that this structure is in file.json, we can add keys with something like:

// pega o conteúdo do file.json e transforma em um php array
$data = json_decode(file_get_contents('file.json'), true);
// adiciona "José" sob a id "8dhus8763"
$data['8dhus8763'] = ['nome' => 'José'];
// salva seu novo JSON
file_put_contents(json_encode($data));

The idea is basic: get the contents of JSON - > transforms the JSON string into a PHP array - > adds the object with "name": "Joseph" in the array, with the id "8dhus8763" - > transforms your PHP array into a JSON string - > saves the JSON string in the original file.

    
28.01.2016 / 17:37