Welcome to a beginner’s tutorial and examples of JSON in PHP and Javascript. So you have heard of this “JSON” thing somewhere and wondering what it is used for?
- JSON stands for Javascript Object Notation. In simple terms, we use JSON to convert an array into a string and vice-versa.
- In PHP:
$colors = ["Red", "Green", "Blue"];
- JSON encode to turn an array into a string –
$json = json_encode($colors);
- JSON decode to turn the encoded string back into an array –
$colors = json_decode($json);
- In Javascript:
var colors = ["Red", "Green", "Blue"];
var json = JSON.stringify(colors);
var colors = JSON.parse(json);
That covers the basics, but the usage of JSON is very wide. Let us walk through some examples in this guide – Read on!
ⓘ I have included a zip file with all the source code at the start of this tutorial, so you don’t have to copy-paste everything… Or if you just want to dive straight in.
TLDR – QUICK SLIDES
Fullscreen Mode – Click Here
TABLE OF CONTENTS
DOWNLOAD & NOTES
Firstly, here is the download link to the example code as promised.
QUICK NOTES
If you spot a bug, feel free to comment below. I try to answer short questions too, but it is one person versus the entire world… If you need answers urgently, please check out my list of websites to get help with programming.
EXAMPLE CODE DOWNLOAD
Click here to download all the source code, I have released it under the MIT license, so feel free to build on top of it or use it in your own project.
PHP JSON EXAMPLES
All right, let us now get into the examples of using JSON in Javascript, PHP, and MySQL.
EXAMPLE 1) PHP JSON ENCODE-DECODE
<?php
// (A) AN ARRAY
$person = [
"name" => "Job Doe",
"email" => "job@doe.com"
];
// (B) JSON ENCODE - ARRAY TO STRING
$person = json_encode($person);
echo $person; // STRING
// (C) JSON DECODE - STRING TO ARRAY
$person = json_decode($person, 1);
print_r($person); // ARRAY
As in the introduction:
json_encode()
Turns an array into a string.json_decode()
Turns a JSON-encoded string into an array.
EXAMPLE 2) JAVASCRIPT JSON ENCODE-DECODE
// (A) AN ARRAY
var person = {
name : "Joe Doe",
email : "joe@doe.com"
};
// (B) JSON ENCODE - ARRAY TO STRING
person = JSON.stringify(person);
console.log(person); // STRING
// (C) JSON DECODE - STRING TO ARRAY
person = JSON.parse(person);
console.log(person); // ARRAY (OBJECT)
The same in Javascript, but JSON “encode/decode” is called “stringify/parse”.
JSON.stringify()
Turns an array into a string.JSON.parse()
Turns a JSON-encoded string into an array.
EXAMPLE 3) SEND ARRAY FROM JAVASCRIPT TO PHP
3A) JAVASCRIPT – ENCODE ARRAY TO STRING
// (A) JSON ENCODE ARRAY TO STRING
var person = JSON.stringify({
name : "Joi Doe",
email : "joi@doe.com"
});
// (B) APPEND JSON ENCODED PERSON TO DATA
var data = new FormData();
data.append("person", person);
// (C) SEND DATA TO SERVER
fetch("3b-receive.php", { method:"POST", body:data })
.then(res => res.text())
.then(txt => console.log(txt));
What’s the big deal with JSON? With the default POST or GET, it is impossible to directly send an array or object across. This is where we use JSON.stringify()
to turn an array into a string, then send it over to the server.
3B) PHP – DECODE STRING TO ARRAY
<?php
// (A) $_POST["PERSON"] IS A STRING
echo $_POST["person"];
// (B) JSON DECODE TO GET BACK AS ARRAY
$person = json_decode($_POST["person"], true);
print_r($person);
This should be pretty self-explanatory. We simply use json_decode()
on the server side to turn the string back into an array.
EXAMPLE 4) JAVASCRIPT FETCH ARRAY FROM PHP
4A) JAVASCRIPT – FETCH FROM PHP
// (A) FETCH FROM SERVER
fetch("4b-fetch.php")
.then(res => res.json())
.then(arr => console.log(arr));
In this example, we will be fetching JSON data from PHP instead of sending it.
4B) PHP – OUTPUT JSON ENCODED ARRAY
<?php
// (A) ARRAY
$person = [
"name" => "Jon Doe",
"email" => "jon@doe.com"
];
// (B) OUTPUT IN JSON
echo json_encode($person);
Not much of a mystery here. We use json_encode()
to output the array as a string; Javascript will pick this up and decode it back.
EXAMPLE 5) SEND ARRAY FROM SERVER-TO-SERVER
<?php
// (A) JSON ENCODE - ARRAY TO STRING
$person = json_encode([
"name" => "Jor Doe",
"email" => "jor@doe.com"
]);
// (B) SEND TO "OTHER SERVER"
$url = "http://localhost/3b-receive.php"; // CHANGE URL TO YOUR OWN
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, ["person" => $person]);
$result = curl_exec($ch);
curl_close($ch);
print_r($result);
Captain Obvious to the rescue, we can also use JSON in a server-to-server call.
- There is a
$person
array. - It is impossible to directly send this to another server, so we
json_encode($person)
to turn it into a string first. - Finally, use CURL to send it out.
EXAMPLE 6) STORE JSON WITH MYSQL
6A) DUMMY DATABASE TABLE
CREATE TABLE `dummy` (
`id` bigint(20) NOT NULL,
`name` text NOT NULL,
`fav` text NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
ALTER TABLE `dummy`
ADD PRIMARY KEY (`id`);
ALTER TABLE `dummy`
MODIFY `id` bigint(20) NOT NULL AUTO_INCREMENT;
For this last example, we will be working with JSON and MySQL – Start by creating this dummy table. Only 3 fields here :
id
Primary key, just a running number.name
Name of person.fav
An array of the person’s favorite stuff.
6B) INSERT-RETRIEVE JSON FROM THE DATABASE
<?php
// (A) CONNECT TO DATABASE - CHANGE SETTINGS TO YOUR OWN
define("DB_HOST", "localhost");
define("DB_NAME", "test");
define("DB_CHARSET", "utf8mb4");
define("DB_USER", "root");
define("DB_PASSWORD", "");
$pdo = new PDO(
"mysql:host=". DB_HOST .";charset=". DB_CHARSET .";dbname=". DB_NAME,
DB_USER, DB_PASSWORD
);
// (B) SAVE - JSON ENCODE TO A STRING
$stmt = $pdo->prepare("REPLACE INTO `dummy` (`id`, `name`, `fav`) VALUES (?,?,?)");
echo $stmt->execute([
1, "Joy Doe", json_encode(["Red", "Green", "Blue"])
]) ? "OK" : "ERROR";
// (C) FETCH - JSON DECODE TO GET BACK ARRAY
$stmt = $pdo->prepare("SELECT `fav` FROM `dummy` WHERE `id`=?");
$stmt->execute([$id]);
$fav = $stmt->fetchColumn();
$fav = json_decode($fav);
print_r($fav);
Remember that json_encode()
produces a string? Yes, we can JSON encode an array, then store the string into the database as-it-is.
EXTRA BITS & LINKS
That’s all for the tutorial, and here is a small section on some extras and links that may be useful to you.
LINKS & REFERENCES
- JSON Encode | JSON Decode – PHP
- Send Array From HTML To PHP – Code Boxx
INFOGRAPHIC CHEATSHEET

THE END
Thank you for reading, and we have come to the end of this guide. I hope that it has helped you to better understand JSON, and if you have anything to share with this guide, please feel free to comment below. Good luck and happy coding!