Reputation: 151
I want to append { "pname":"superman" , "pid":"4" }
to the obdatabase.json. But my attempt below completely overwrite the json file.
How do I modify this?
obdatabase.json
{ "pobject":[{ "pname":"Pikachu" , "pid":"1" },
{ "pname":"squirtle" , "pid":"2" },
{ "pname":"Justinbieber" , "pid":"3" }]}
add.php
<?php
$file="obdatabase.json";
$json = json_decode(file_get_contents($file),TRUE);
$json['pobject'] = array('pname'=>'Superman', 'pid'=>4);
file_put_contents('obdatabase.json', json_encode($json));
?>
Upvotes: 0
Views: 3197
Reputation: 11689
In your code, you write:
$json['pobject'] = array('pname'=>'Superman', 'pid'=>4);
By this way, you replace the $json['pobject']
array instead of adding a value.
You have to use this syntax:
$json['pobject'][] = array('pname'=>'Superman', 'pid'=>4);
Then, you can overwrite old text file with:
file_put_contents( 'obdatabase.json', json_encode( $json ) );
You have already asked for this question here. The correct way to act on Stack Overflow is:
This out of respect for users that dedicate their time to find a solution and out of respect for future visitors that can easy understand if a question has a valid answer or not.
Upvotes: 4
Reputation: 4207
The idea is you get gthe json from the file then parse it to php json_encode()
Upvotes: 0