ltjfansite
ltjfansite

Reputation: 460

Edit JSON file using PHP

I'm trying to edit a JSON file using php, I've set up a little ReactJS app has form elements.

My JSON is as follows

[
    {
        "id": 1,
        "Client": "client 1",
        "Project": "project 1",
        "StartDate": "2018\/11\/02 16:57:35",
        "CompletedDate": "",
        "projectUrl": "project-1"
    },
    {
        "id": 2,
        "Client": "client 2",
        "Project": "project 2",
        "StartDate": "2018\/11\/02 16:57:35",
        "CompletedDate": "",
        "projectUrl": "project-2"
    },
    {
        "id": 3,
        "Client": "client 3",
        "Project": "project 3",
        "StartDate": "2018\/11\/02 16:57:35",
        "CompletedDate": "",
        "projectUrl": "project-3"
    }
]

So far i have code to create a new "project" at the end of the file. My PHP is as follows

if ($_SERVER["REQUEST_METHOD"] == "POST")
{

    try {

        $clientName =  $_POST['clientName'];
        $ProjectName =  $_POST['projectName'];
        $url =  strtolower($_POST['url']);
        $date = date('Y/m/d H:i:s');


        $message = "";
        $url = '../json/projects.json';

        if( file_exists($url) )

        if(file_exists('../json/projects.json'))
        {
            $current_data = file_get_contents('../json/projects.json');  
            $array_data = json_decode($current_data, true);  
            $extra = array(  
                'id' => count($array_data) + 1, 
                'Client' => $clientName, 
                'Project' => $ProjectName, 
                'StartDate' => $date, 
                'CompletedDate' => "",
                'projectUrl' => $projectFileName + ".json"
            );  
            $array_data[] = $extra;  
            $final_data = json_encode($array_data, JSON_PRETTY_PRINT);  
            if(file_put_contents('../json/projects.json', $final_data))  
            {  
                 $message = "sent";  
            }  
            else  
            {
                $message = "notSent";
            }
        }
        else
        {
            $message = "jsonFileNotFound";
        }


        $response = $message;

    } catch (Exception $e) {
        $response = $e->getMessage();
    }

    echo $response;

}

What i can figure out is how to edit lets say "CompletedDate" value to todays date with a click of the button.

I have an hidden input field on my page that has the project ID in, so what I'm after is helping getting that id, matching it to the JSON, then editing the completed date that matches the ID.

This PHP will fire using ajax so i can pass the ID pretty easy.

Upvotes: 0

Views: 749

Answers (1)

Nigel Ren
Nigel Ren

Reputation: 57131

Using similar code to what you already use, you can update the relevant data by using the ID as the index into the decoded JSON file. As ID 1 will be the [0] element of the array, update the [$id-1] element with the date...

if ($_SERVER["REQUEST_METHOD"] == "POST")
{
    try {

        $id = 2;   // Fetch as appropriate
        $date = date('Y/m/d H:i:s');
        $url = '../json/projects.json';

        if( file_exists($url) )
        {
            $current_data = file_get_contents($url);
            $array_data = json_decode($current_data, true);
            $array_data[$id-1]['CompletedDate'] = $date;
            $final_data = json_encode($array_data, JSON_PRETTY_PRINT);
            if(file_put_contents($url, $final_data))
            {
                $message = "updated";
            }
            else
            {
                $message = "notUpdated";
            }
        }
        else
        {
            $message = "jsonFileNotFound";
        }


        $response = $message;

    } catch (Exception $e) {
        $response = $e->getMessage();
    }

    echo $response;

}

You may need to tweak some of the bits - especially how the ID is picked up ($_GET?) and any messages you want.

I've also updated the code to make more consistent use of $url as opposed to hard coding it in a few places.

Upvotes: 1

Related Questions