Eric.18
Eric.18

Reputation: 473

Modifying json with PHP not saving/updating

I am trying to modify data in a json file with php. The code I am using is below. It is able to successfully ready the file contents and in the foreach loop it will echo out in the if statement.

This is great, the if statement is hardcoded for now to test. What I want to do is modify various properties and write it back to the file. This does not seem to be working. When I load the page, then refresh to see if the new value was set it just keeps echoing the same values. I download the .json locally and nothing has changed.

Any thoughts on what I am doing wrong?

//Get file, decode
$filename = '../json/hartford.json';
$jsonString = file_get_contents($filename);
$data = json_decode($jsonString, true);

foreach ($data['features'] as $key => $segment) {

    if ($segment['properties']['UID'] == '25301') {

//echo out properties for testing
        echo("KEY: ".$key."<br/>");
        echo("UID: ".$segment['properties']['UID']."<br/>");
        echo("Full Name: ".$segment['properties']['FULLNAME']."<br/>");
        echo("FCC: ".$segment['properties']['FCC']."<br/>");
        echo("Render CL: ".$segment['properties']['RENDER_CL']."<br/>");
        echo("<hr/>");

 //set property to new value.... NOT WORKING?
        $segment['properties']['RENDER_CL'] = 111;
    }
}

//Test if file is writable to be sure
$writable = ( is_writable($filename) ) ? TRUE : chmod($filename, 0755);

if ( $writable ) {
    $newJsonString = json_encode($data);
    if (file_put_contents($filename, $newJsonString)) {
        echo('Put File Content success');
    } else {
        echo('NOT put');
    }
} else {
    echo 'not writeable';
}

In the end it will echo out 'Put File Content success' which seems to indicate it was successful but it isn't... Thanks for any advice.

Upvotes: 3

Views: 408

Answers (2)

Przemek
Przemek

Reputation: 123

You should use $segment variable in foreach as a reference:

foreach ($data['features'] as $key => &$segment) {

    ...

    $segment['properties']['RENDER_CL'] = 111;
}

Upvotes: 2

Martin Heraleck&#253;
Martin Heraleck&#253;

Reputation: 5789

You need to understand how foreach cycle works. The thing is, that the value you're getting ($segment) is a copy of the real value in the source array. So when you assign to it ($segment['properties']['RENDER_CL'] = 111;), you don't really change the source array. You only change some local variable that goes out of scope when the cycel-loop ends.

There are several ways how to solve this issue. One of them is to add & before the value-variable:

foreach ($data['features'] as $key => &$segment)

This tells it to use the reference of the array-item, not to copy its value.

Upvotes: 7

Related Questions