Edit json files with php
Updated: 07-Jul-2022 / Tags: PHP and JSON / Views: 2140 - Author: George
Introduction
This article is all about php and json. Most of the time when we build a website, we are gonna have a folder with a bunch of json files inside. Those json files are containing information that usually is spread throughout the whole website, like the brandname, or the contact details, or details about the website's owner. So when we have to make changes, lets say the email address has changed, we go to the json file and change the email address there.
But this is not what programmers do.
So in this tutorial we are going to build a php application with which we are going to
fetch the data from the json files and edit them.
Everything will work dynamic, we don't need to know the names of the json files, or any of the properties or values inside them.
Sometimes when we have to explain dynamic actions, it gets a little bit complicated because everything is so general.
I hope i got it right.
If not please leave a comment on what was hard to understand. So i can re-write those parts.
And with that said, lets begin with the projects structure and the files we have.
Projects structure
Let's see the files that we need.
/-- root |-- index.php |-- script.php |-- styles.css /-- json-files/ |-- admin.json |-- founder.json |-- settings.json
- Inside the websites root folder we have an index file where we are going to design the application's layout.
- We are gonna have a script.php file, to write the php code.
-
And a styles.css file to make things a little bit pretty.
*{ margin: 0; padding: 0; box-sizing: border-box; font-size: 18px; color: #555; } body{ font-family: sans-serif; min-height: 100%; padding: 20px; } .page{ display: grid; grid-template-columns: auto 1fr; grid-column-gap: 150px; max-width: 900px; margin: 0 auto; } .title{ margin-bottom: 50px; padding-bottom: 7px; border-bottom: thin solid #e4e4e4; } .title span{ color: #3b57b0; } .form-group{ margin-bottom: 10px; } input[type=text]{ padding: 7px; border: thin solid #d4d4d4; } input:focus{ outline: none; } form{ margin-top: 10px; } label{ display: inline-block; width: 100px; margin-right: 10px; } button{ padding: 7px; border: thin solid #d4d4d4; cursor: pointer; } button:hover{ background-color: #00b300; color: white; } .files a{ display: block; margin-top: 5px; text-decoration: none; color: #3b57b0; } .files a:hover{ text-decoration: underline; }
Next we have a json-files folder with the json files inside.
Let's see what's in those files.
In the admin.json file we have information stored about our website's administrator.
{
"Name": "Dennis",
"Username": "admin",
"Password": "admin",
"Email": "dennis@mail.com",
"Status": "active"
}
In the founder.json file we have information about the website's owner.
{
"Name": "George",
"Mobile": "777-777-7777",
"City": "Athens Greece",
"Street": "Somewhere in Athens 111",
"Email": "mail@mail.com"
}
And in the settings.json file we have some general settings that we apply to the website.
{
"Theme": "dark",
"Lang": "En",
"Font-size": "16",
"Font-family": "ubuntu"
}
Now that we got familiar with the project's structure and the json files, lets take a look at the application and let's start coding.
The application
The applications interface as you see below is split in two sections. In the left section we are fetching the
filenames from the json-files/ folder and display them as links.
And when we click on one of them, we will display in the right section the file's information inside input fields,
so we can edit them.
Click on a filename to see the content of that file.
Now let's start from the index.php file.
The index.php file
The first thing that we do in the index.php file is to include our php file, so we get access to the php code that we will write there.
<?php include "script.php"; ?>
Next we are going to write a basic html structure with a link to the css file in line 7.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="styles.css">
<title>Edit JSON files with php</title>
</head>
<body>
</body>
</html>
Next inside the body tags i will put a div element with a class of "page". This element will hold all the html code we need to layout our application.
<body>
<div class="page"> <!-- The app wrapper -->
</div>
</body>
Next i will split the "page" in two sections.
I will have a div element with a class of "files" in line 12, this is going to
be the left section where we are displaying the json file names.
And i will have another div element with a class of "edit-section" in line 13, in which we are going to display the json values inside input fields.
<div class="page"> <!-- The app wrapper -->
<div class="files"></div>
<div class="edit-section"></div>
</div>
The left section
Now let's go inside the first div element with the class of "files", and write the php code to fetch the json file names from the json-files folder.
Let's put a title to the files section in line 13, and open php tags in line 14 to write our php code.
Our task here is to fetch the json file names from the json-files folder and display them as links.
<div class="files">
<div class="title">Json files</div>
<?php
?>
</div>
To fetch the json file names we are going to use the glob function in line 15.
<?php
$files = glob("json-files/*.json");
?>
The glob()function find's pathnames matching a pattern like the one we have here as an argument, "json-files/*.json".
In our case here we are saying to the glob() function to fetch all files
with a .json extension from the json-files folder.
The function returns an array containing the matching filepaths, or an empty array if nothing matches the pattern.
Next we are going to loop through the $files array and fetch every filepath that the array contains.
<?php
$files = glob("json-files/*.json");
foreach ($files as $value) {
}
?>
But let's first take a look inside the $files array.
We see that the $files array is holding the filepaths to the json files. That is not what we want to display, we only want the file name.
$files = [ "json-files/admin.json", "json-files/founder.json", "json-files/settings.json", ]
So in line 17 we are using the basename function to get from the filepath the file's name.
<?php
$files = glob("json-files/*.json");
foreach ($files as $value) {
$value = basename($value);
}
?>
Next i am going to display the filename inside an a tag as a link in line 18. And i am going to add a query string inside the href attribute that will send in the same page the file's name.
By doing so i will be able to catch the file name in the right section.
foreach ($files as $value) {
$value = basename($value);
?>
<a href="?file=<?php echo $value ?>">
<?php echo $value ?>
</a>
<?php
}
?>
If we reload the index file we will have the below result.
We will have the json file names displayed as links in the left section.
The right section
The next step is to catch the query string that we send when we click on a file name and we will do that from inside the "edit-section" section.
In line 14, as we did in the left section we will have a div element with a class of "title" to display the current file name. I will use the superglobal GET['file'] variable to catch the file's name.
And in line 15 we are opening php tags to write the php code.
<div class="edit-section">
<div class="title">Edit properties in - <?php echo @$_GET['file'] ?> </div>
<?php
?>
</div>
Inside the php tags we will first check if there is a GET request, and specific if there is a ['file'] key in line 16. The ['file'] key is holding the file name.
<?php
if(isset($_GET['file'])){
}
?>
If this is true, if there is a GET request, then in line 17 we create a variable named $file, and we assign the file name to it.
<?php
if(isset($_GET['file'])){
$file = $_GET['file'];
}
?>
Next in line 18 we use the file_get_contents function to fetch the data from the json file using the file name from the GET request.
$file = $_GET['file'];
$file = file_get_contents("json-files/{$file}");
The data that we fetch are in a json format, which basically is a string. So we have to decode the json data in a php array so we can work with them.
That's why we use the json_decode function in line 19, to convert the json data and store them in the $enc_file variable.
$file = $_GET['file'];
$file = file_get_contents("json-files/{$file}");
$enc_file = json_decode($file, true);
The keyword true as the second argument of the json_decode function, will decode the data to an array, if we omit it the function will return an object.
Next in line 20 we are going to loop through the $enc_file array and fetch the keys and the values with the foreach function.
$file = $_GET['file'];
$file = file_get_contents("json-files/{$file}");
$enc_file = json_decode($file, true);
foreach ($enc_file as $key => $value) {
}
Now, next inside the loop i will use a form element for every key, value pair.
foreach ($enc_file as $key => $value) {
?>
<form action="?<?php echo $_SERVER['QUERY_STRING']?>" method="POST" >
<label><?php echo $key ?></label>
<input type="text" name="<?php echo $key ?>" value="<?php echo $value ?>" >
<button type="submit" name="submit" value="save">Save</button>
</form>
<?php
}
Code breakdown
- action="?<?php echo $_SERVER['QUERY_STRING']?>"... that means that the form will submit the data to the same page sending back the url's query string. We do this because the query string contains the file name and we need the file name to edit the data in the php file. You will see when we get to the php file.
- method="POST"... means that we are going to use the POST HTTP method to send the data to the php file. That means also that we have to check for a POST request in the php file.
-
name="<?php echo $key ?>" value="<?php echo $value ?>"... in line 21 we set the name attribute equal to the
$key, and the value attribute equal to the $value.
When we have a key, value pair like this "Street" => "Somewhere in Athens 111", the $key = "Street", and the $value = "Somewhere in Athens 111".
Now if you run the index file and click on a file name you will see the keys displayed as labels, and the values inside input elements.
Now lets go to the php file to catch and save the edited values.
The php file
In the php file we are gonna save the input value when we click on the save button.
<?php
if(isset($_POST['submit'])){
$data = $_POST;
$file = $_GET['file'];
foreach ($data as $key => $input) {
if($key != "submit"){
$json_data = file_get_contents("json-files/{$file}");
$dec_data = json_decode($json_data, true);
foreach ($dec_data as $field => $value) {
if($key == $field){
$dec_data[$key] = trim($input);
}
}
}
}
$enc_data = json_encode($dec_data, JSON_PRETTY_PRINT);
file_put_contents("json-files/{$file}", $enc_data);
}
Code breakdown
-
First of all we are going to check if we have a POST request in line 2
if(isset($_POST['submit'])){
-
If this is true we are going to assign the incoming data to the $data variable in line 3. The $data variable is now an associative array.
And in line 4 we grab the file name from the URL with the GET method by targeting the ['file'] key.
$data = $_POST; $file = $_GET['file'];
-
Lets see what the $data array holds.
We see that by clicking on the save button we get the names and values of the submit button and the input's field. We are interested only in the first entry, not in the submit button. We will see this down below.
// Something like this, depending on what field you click on. $data = [ 'Street' => 'Somewhere in Athens 111', 'submit' => 'save', ]
-
Next we are going to loop through the $data array to fetch the key and the value.
foreach ($data as $key => $input) {
-
Next inside the loop i will grab everything else, except the submit button.
if($key != "submit"){
-
Inside the if statement i will grab the contents of the json file, by using the file name that the $file variable holds, in line 7.
And in line 8 i will convert the json data to an array, and store them in the $dec_data variable.
$json_data = file_get_contents("json-files/{$file}"); $dec_data = json_decode($json_data, true);
-
The $dec_data variable is an associative array that holds the content of the file that we clicked on to edit.
$dec_data = [ 'Name' => 'George', 'Mobile' => '777-777-7777', 'City' => 'Athens Greece', 'Street' => 'Somewhere in Athens 111', 'Email' => 'mail@mail.com', ]
-
Next i will loop through the $dec_data array in line 10.
I will find the value that i want to update, by checking if the $key from the first foreach loop matches the $field variable from the second loop.
The $key variable is holding the incoming input name attributes, and the $field variable is holding the keys from the json file.
And if we have a match we will update the value in line 12.
foreach ($dec_data as $field => $value) { if($key == $field){ $dec_data[$key] = trim($input); } }
-
And last outside from both foreach loops, we encoding the data back to json in line 18.
And we write the data back to the file in line 19.
$enc_data = json_encode($dec_data, JSON_PRETTY_PRINT); file_put_contents("json-files/{$file}", $enc_data);
-
And that's it we completed the application. We can edit now any json file without knowing the file's name or the keys, or the values that the file has.
Summary
In this tutorial we coded an application to edit json files.
We saw how to fetch the data from the json files and display them inside input fields so we can update the values.
Also we saw how to structure the application's layout with HTML and CSS.
Last Words
Thanks for reading, i hope you find the article helpful.
Please leave a comment if you find any error's, so i can update the page with the correct code.
Source code
You can download the source code and use it in any way you like.
Times downloaded: 424
Comment section
You can leave a comment, it will help me a lot.
Or you can just say hi. 😉