Append Data to a .Json File With PHP

Append data to a .JSON file with PHP


$data[] = $_POST['data'];

$inp = file_get_contents('results.json');
$tempArray = json_decode($inp);
array_push($tempArray, $data);
$jsonData = json_encode($tempArray);
file_put_contents('results.json', $jsonData);

Append data to Json from PHP

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.

append data to json file php

As $api->me() returns object - you cannot write it to a file directly. You should convert object to a string. Simple way is to json_encode it:

$file = "users.json";
$json = json_decode(file_get_contents($file), true);
$file = fopen($file,'w+');
fwrite($file, json_encode($api->me()));
fclose($file);

Next problem - is overwriting data. As you open file with w+ - you file gets truncated to 0 length.

Solution here depends on what you need with previous data. If you want to rewrite some data - I think current behaviour does it already.

If you want to append data to a file - you should use another mode when you open file, for example a+. But in this case, file contents won't be correct json, as you write to file not a single json string, but several strings, which is not correct json. So, it's up to you to find a proper solution.

Update:

According to file name, I suppose you store users in it. So, I think there's a list of users, encoded in json. So, a brief solution can be:

$file = "users.json";
$json = json_decode(file_get_contents($file), true);

// Now $json stores list of you current users. I suppose it's a simple array of arrays

// This is data for a new user
$new_user = $api->me();

// as data `$new_user` is object, I think you need to convert it to array
// this can be done as:
$new_user = json_decode(json_encode($new_user), true);

// now, add new user to existsing array
$json[] = $new_user;

$file = fopen($file,'w+');

// now we can encode `$json` back and write it to a file
fwrite($file, json_encode($json));
fclose($file);

Append form data to json file using php

If you really believe this is what you want then is this any good to you

<?php
session_start();
if(isset($_POST['add'])){
$data = file_get_contents('members.json');
$data_array = json_decode($data);
//data in our POST

$data_array[] = $_POST['id'];
$data_array[] = $_POST['firstname'];
$data_array[] = $_POST['lastname'];
$data_array[] = $_POST['address'];
$data_array[] = $_POST['gender'];

$data_array = json_encode($data_array, JSON_PRETTY_PRINT);

file_put_contents('members.json', $data_array);
$_SESSION['message'] = 'Data successfully appended';
}
else{
$_SESSION['message'] = 'Fill up add form first';
}
header('location:index.php');
?>

You could sexy that up a bit assuming you want all the data items from $_POST like this.

<?php
session_start();
if(isset($_POST['add'])){
$data = file_get_contents('members.json');
$data_array = json_decode($data);
//data in our POST

foreach ($_POST as $v) {
$data_array[] = $v;
}

$data_array = json_encode($data_array, JSON_PRETTY_PRINT);

file_put_contents('members.json', $data_array);
$_SESSION['message'] = 'Data successfully appended';
}
else{
$_SESSION['message'] = 'Fill up add form first';
}
header('location:index.php');
?>

Append json file with array using php

You have to decode your file to append your datas :

$data = json_decode(file_get_contents('data.json'), true);
$data[$thisId] = array(
'userId'=> $userId,
'username'=> $username,
'password'=> $password,
);
$json = json_encode($data);
file_put_contents('data.json', $json);

How to Append JSON File in PHP?


<?php
if(file_exists("upload.json"))
{
$temp_array = array();
$temp_array = json_decode(file_get_contents('upload.json'));
$upload_info = array('media_name'=>'b','media_category'=>'v','media_info'=>'c','media_location'=>'x','media_artist'=>'z');
array_push($temp_array->upload->image, $upload_info);
file_put_contents('upload.json', json_encode($temp_array));
}
else
{
$upload_info = array();
$upload_info['upload']['image'][] = array('media_name'=>'b','media_category'=>'v','media_info'=>'c','media_location'=>'x','media_artist'=>'z');
$json = json_encode($upload_info);
$file = "upload.json";
file_put_contents($file, $json);
}
?>

This one just work for you!

append data to json file using PHP and AJAX

You are appending in the wrong place.

You should append the new values to the inner 'LogIns` array, but instead you are appending to it's container.

<?php

$string = ' {
"LogIns":[
{
"Username":"Mike","password":"123"
},
{
"Username":"Farrah","password":"123"
},
{
"Username":"John","password": "123"
}
]
}';

$array = json_decode($string,true);

$extra = [
'Username' => 'John',
'password' => 'doe123'
];

$array['LogIns'][] = $extra;

print_r($array);

Will output nicely:

Array
(
[LogIns] => Array
(
[0] => Array
(
[Username] => Mike
[password] => 123
)

[1] => Array
(
[Username] => Farrah
[password] => 123
)

[2] => Array
(
[Username] => John
[password] => 123
)

[3] => Array
(
[Username] => John
[password] => doe123
)

)

)

If you do a json_encode on the final array you will get the following

{
"LogIns": [{
"Username": "Mike",
"password": "123"
}, {
"Username": "Farrah",
"password": "123"
}, {
"Username": "John",
"password": "123"
}, {
"Username": "John",
"password": "doe123"
}]
}

Also see the use of []= instead of array_push which takes away the overhead of using a function.

Your next questions:

  1. removing objects from a json objects
    Simply decode the initial json string into an array and operate on the array, remove items with unset,

    ex. unset($array['LogIns'][2]) will remove the element with key 2

  2. overwriting a file

    file_put_contents already does that, if you do want to append to the file instead you need to pass the FILE_APPEND flag

Append php loop data to JSON object

You set your $dataArr inside the while-loop. So each time the loop is runs, it will be overwritten. Also, it makes more sense and it's much more clear when you handle it as an array (or object) and afterwards convert it to JSON.

$dataArr = array(array('name' => 'Dylan', 'page_link' => 'https://mypage.com/'));

foreach($uniqueFranchise_id as $franchise)
{
$sqlFranchise = "select * from franchise where franchise_id = $franchise";
$resultFranchise = $conn->query($sqlFranchise);
if($resultFranchise->num_rows > 0)
{
while($rowFranchise = $resultFranchise->fetch_assoc())
{
$dataArr[] = array('name' => $rowFranchise['name'], 'page_link' => $rowFranchise['page_link']);
}
}
}

$json = json_encode($dataArr);
echo $json;

Append data to JSON array using PHP

$accountData is an object, as it should be. Array access is not valid:

array_push($accountData->loginHistory, $newLoginHistory);
// or simply
$accountData->loginHistory[] = $newLoginHistory;


Related Topics



Leave a reply



Submit