3

I have a simple json file that has a direct image link and the folder name per json object:

[
        {
                "image": "http://placehold.it/350x150",
                "folder": "Small"
        },
        {
                "image": "http://placehold.it/450x250",
                "folder": "Medium"
        },
        {
                "image": "http://placehold.it/550x350",
                "folder": "Medium"
        }
]

I would like to append those two values from a post, but the result is an unchanged json file. Here is the PHP code w/ comments:

$directLink = $_POST['txtDirectLink'];
$category = $_POST['selectCategoriesImages'];
$util->addToJsonImageList($directLink, $category);

//decodes the json image list, merges to the decoded array a new image, then encodes back to a json file
function addToJsonImageList($link, $category) {
    $file = file_get_contents('./images_list.json', true);
    $data = json_decode($file);
    unset($file);

    $newImage = array('image' => $link, 'folder' => $category);
    //$newImage['image'] = $link;
    //$newImage['folder'] = $category;
    $result = array_merge((array)$data, (array)$newImage);

    json_encode($result);
    file_put_contents('./images_list.json', $result);
    unset($result);
}

The logic is that it should be simple to json_decode the file as an array, merge the new array onto that, then encode the result and put into the same file. I've been unable to capture any sort of errors either.

benbob
  • 55
  • 1
  • 1
  • 7

4 Answers4

9
$data = json_decode($file, true);
//When TRUE, returned objects will be converted into associative arrays.
unset($file);

$newImage = array('image' => $link, 'folder' => $category);
//$newImage['image'] = $link;
//$newImage['folder'] = $category;
$result = array_merge($data, $newImage);
//don't need to cast

Reference PHP json_decode Manual

Edit The following code works (tested)

function addToJsonImageList($link, $category) {
    $file = file_get_contents('./images_list.json', true);
    $data = json_decode($file,true);
    unset($file);
    //you need to add new data as next index of data.
    $data[] = array('image' => $link, 'folder' => $category);
    $result=json_encode($data);
    file_put_contents('./images_list.json', $result);
    unset($result);
}

Edit 2 added lot of error reporting and debugging. Please let me know the output of the following. The code below is not tested (just typed in here).please fix if you find any syntax error. it is late here and can only check tomorrow my time, but can reply.

<?php
//display all errors and warnings
error_reporting(-1);
addToJsonImageList('test link', 'test category');

function addToJsonImageList($link, $category) {
    $file = file_get_contents('./images_list.json', true);
    if ($file===false)die('unable to read file');
    $data = json_decode($file,true);
    if ($data ===NULL)die('Unable to decode');
    unset($file);
    echo "data before\n";
    var_dump ($data);
    //you need to add new data as next index of data.
    $data[] = array('image' => $link, 'folder' => $category);
    echo "data after\n";
    var_dump ($data);
    $result=json_encode($data);
    if (file_put_contents('./images_list.json', $result) === false){
        die('unable to write file');
    }
    unset($result);
}
?>
bansi
  • 55,591
  • 6
  • 41
  • 52
  • I receive a "array_merge: argument #1 is not an array" error now. – benbob Aug 19 '13 at 05:57
  • I tried the edited code and it still didn't change my json file.. Is there an error check I can use to see where the problem is? The json file is in the same directory as this code too. – benbob Aug 19 '13 at 14:22
  • Awesome, with your error checking I was able to get it to work. There is one thing I noticed differently about the json file after though: Any http:// strings turned into http:\/\/ (does encoding do that?). Thanks for the help and time, I'll look into the escape slashes – benbob Aug 20 '13 at 03:25
  • nice to hear it worked for you. Forward slashes are escaped even though it is not required in JSON. check this post for more detailed discussion. http://stackoverflow.com/questions/1580647/json-why-are-forward-slashes-escaped – bansi Aug 20 '13 at 03:48
  • glad to hear it can be safely ignored :) – benbob Aug 21 '13 at 00:36
  • I tried the first edit and it worked, but how can I append at the start of the json array? – pavitran Feb 17 '17 at 16:28
1

Lets say you have this .json file named (playerJson)

{

"Players":
   [
     {"Name":"Arun","Arm":"Gun","num":"1"},
     {"Name":"sssv","Arm":"Arc","num":"2"},
     {"Name":"Surya","Arm":"Bomb","num":"3"},
     {"Name":"sssv","Arm":"Fire","num":"4"}

   ]
}

Now what we have to do in php (myPhpFile.php) is : (I suppose you are loading your data from a form)

<?php

$json = file_get_contents('playerJson.json');
$json_data = json_decode($json,true);

$newar = array(
           'Name'=>$_POST['nameField'] ,
           'Arm' =>$_POST['armField'],
           'Num' =>$_POST['numField']
);
//saving data in Players object...
array_push($json_data['Players'], $newar);

$json = json_encode($json_data);

file_put_contents('playerJson.json', $json);

?>

That's all ! You have a new line in your "Players" Object. But if you want to add a new object, avoid the [Players] after $json_data in the array_push function.

Shadoworker
  • 191
  • 1
  • 7
0

What you can do is decode json and then merge them.

$data = json_decode(file_get_contents(./images_list.json));

$result = array_merge((array)$data, (array)$newImage);

and then just output json_encode

file_put_contents('./images_list.json', json_encode($result, JSON_FORCE_OBJECT));
Dipesh Parmar
  • 27,090
  • 8
  • 61
  • 90
  • I added json_encode(result) inside file_put_content and now am receiving the error: "array_merge(): Argument #1 is not an array", even though I set $data as an array and not an object by adding the optional true – benbob Aug 19 '13 at 05:48
0

your issue is with the following lines of code

json_encode($result);
file_put_contents('./images_list.json', $result);

your not capturing the result of json_encode so your writing an array into the file.

you need to adjust the code to read as follows

$result = json_encode($result);
file_put_contents('./images_list.json', $result);
DevZer0
  • 13,433
  • 7
  • 27
  • 51
  • I should have updated my answer because I had already fixed that problem. Thanks for the insight though. – benbob Aug 19 '13 at 14:18