ryanpika
ryanpika

Reputation: 151

Append data to Json from PHP

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

Answers (2)

fusion3k
fusion3k

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

Edit:

You have already asked for this question here. The correct way to act on Stack Overflow is:

  • If you don't understand the answer(s) or the answer(s) doesn't match your question, continue discussion in the precedent question;
  • If the question is closed, mark an answer as right and then ask for new question.

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

mehany
mehany

Reputation: 4207

The idea is you get gthe json from the file then parse it to php json_encode()

Upvotes: 0

Related Questions