user1773104
user1773104

Reputation: 151

How to Append JSON File in PHP?

<?php
if(file_exists("upload.json"))
{

// For GETTING Values as an Associative Array...
$temp_array = array();
$temp_array = json_decode(file_get_contents('upload.json'),true);

 $upload_info = array('media_name'=>'b', 
 'media_category'=>'v','media_info'=>'c','media_location'=>'x','media_artist'=>'z');

 array_push($temp_array, $upload_info);

 file_put_contents('upload.json', json_encode($upload_info));
 }
else
{
$upload_info =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_encode($json));

}
?>

I can not append JSON File Together : Is there any Solutions ? Thanks in Advance .

I want JSON File in the Following Order.

{
  "upload":
    {
     "image":[
        {
         "media_name": "b",
         "media_category": "v",
         "media_info": "c",
         "media_location": "x",
          "media_artist": "z"
       },
       {
        "media_name": "b",
        "media_category": "v",
        "media_info": "c",
        "media_location": "x",
        "media_artist": "z"
       }
   ]
  }
}

What Should I do ??

Upvotes: 0

Views: 3766

Answers (2)

ecco
ecco

Reputation: 516

<?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!

Upvotes: 3

Jonast92
Jonast92

Reputation: 4967

Try this:

$json_data = json_decode(file_get_contents('data.txt'), true);
for ($i = 0, $len = count($json_data); $i < $len; ++$i) {
    $json_data[$i]['num'] = (string) ($i + 1);
}
file_put_contents('data.txt', json_encode($json_data));

example from here: Parsing JSON file with PHP

Upvotes: 1

Related Questions