A Beginner’s Guide To JSON In PHP – Simple Examples

Welcome to a beginner’s tutorial and examples of JSON in PHP. So you have probably heard of this “JSON” thing somewhere and wondering what it is for?

  • JSON stands for Javascript Object Notation.
  • In simple terms, we use JSON to “convert” an array or object into a string and vice-versa.
    • $jsonstring = json_encode(["Foo", "Bar"]);
    • $array = json_decode($jsonstring);
  • With JSON, we can encode an array in Javascript and send it to the server as a string; On the server-side, we decode to get the array back.
  • We can also use JSON in server-to-server calls to pass arrays around.

That covers the basics, but let us walk through more examples in this guide – Read on!

ⓘ I have included a zip file with all the example code at the end of this tutorial, so you don’t have to copy-paste everything… Or if you just want to dive straight in.

 

 

REAL QUICK SLIDES

 

TABLE OF CONTENTS

Download & Notes PHP JSON Useful Bits & Links
The End

 

DOWNLOAD & NOTES

Firstly, here is the download link to the example code as promised.

 

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.

 

QUICK NOTES

If you spot a bug, please feel free to comment below. I try to answer 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.

 

 

PHP JSON EXAMPLES

All right, let us now get into the examples of using JSON in PHP.

 

1) CLIENT-TO-SERVER JSON

1A) THE JAVASCRIPT

1a-json-send.html
<script>
// (A) DUMMY PERSON
var person = {
  name : "Jon Doe",
  email : "jon@doe.com"
};
 
// (B) JSON ENCODE INTO STRING
person = JSON.stringify(person);
console.log("JSON ENCODED STRING: " + person);
 
// (C) APPEND JSON ENCODED PERSON TO DATA
var data = new FormData();
data.append("person", person);
 
// (D) SEND DATA TO SERVER
var xhr = new XMLHttpRequest();
xhr.open("POST", "1b-json-receive.php");
xhr.onload = function(){ console.log(this.response); };
xhr.send(data);
</script>

First, we have a common example usage of JSON in the world of Javascript. With the default POST or GET mechanism, it is impossible to directly send the var person object across. This is where we use JSON.stringify(person) to turn it into a string, then send it over to the server.

1B) THE PHP

1b-json-receive.php
<?php
// (A) POST DATA RECEIEVED
echo "POST DATA RECEIVED: ";
print_r($_POST);
 
// (B) JSON DECODE TO GET BACK AS ARRAY
$person = json_decode($_POST['person'], true);
echo "JSON DECODED PERSON: ";
print_r($person);

This should be pretty self-explanatory. On the server-side, we simply use json_decode($_POST['person']) to turn the string back into an array.

 

 

2) SERVER-TO-SERVER JSON

2-send.php
<?php
// (A) PERSON ARRAY
$person = [
  "name" => "Jane Doe",
  "email" => "jane@doe.com"
];
echo "RAW PERSON ARRAY: ";
print_r($person);

// (B) JSON ENCODE INTO STRING
$person = json_encode($person);
echo "<br>JSON ENCODED: $person";

// (C) SEND TO "OTHER SERVER"
$url = "http://localhost/1b-json-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);
echo "<br>";
print_r($result);

Now, JSON is a standard format. It does not just apply to client-server, and we can also use it in a server-to-server call. In this example, we are pretty much doing the same:

  • 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.

 

 

3) JSON WITH MYSQL

3A) DUMMY DATABASE TABLE

3a-dummy.sql
CREATE TABLE `dummy` (
  `id` int(11) NOT NULL,
  `name` text NOT NULL,
  `fav` text NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

ALTER TABLE `dummy`
  ADD PRIMARY KEY (`id`);

ALTER TABLE `dummy`
  MODIFY `id` int(11) 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.

3B) INSERT JSON STRING

3b-insert.php
<?php
// (A) CONNECT TO DATABASE - CHANGE SETTINGS TO YOUR OWN
define('DB_HOST', 'localhost'); 
define('DB_NAME', 'test'); 
define('DB_CHARSET', 'utf8');
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) DUMMY DATA 
$name = "Joy Doe";
$fav = ["Red", "Green", "Blue"];
// JSON ENCODE FAVORITES INTO A STRING
$fav = json_encode($fav);

// (C) INSERT INTO DATABASE
$stmt = $pdo->prepare("INSERT INTO `dummy` (`name`, `fav`) VALUES (?,?)");
$stmt->execute([$name, $fav]);
echo "OK";

Remember that json_encode() produces a string? Yes, we can JSON encode an array, then store the string into the database as-it-is.

3C) FETCH & DECODE JSON STRING

3c-fetch.php
<?php
// (A) CONNECT TO DATABASE - CHANGE SETTINGS TO YOUR OWN
define('DB_HOST', 'localhost'); 
define('DB_NAME', 'test'); 
define('DB_CHARSET', 'utf8');
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) FETCH
$id = 1; // CHANGE IF NOT 1
$stmt = $pdo->prepare("SELECT * FROM `dummy` WHERE `id`=?");
$stmt->execute([$id]);
$result = $stmt->fetch();

// (C) OUTPUT RESULTS
echo "RAW SELECT RESULTS FROM DATABASE: ";
print_r($result);
$fav = json_decode($result['fav']);
echo "<br>JSON DECODED FAV: ";
print_r($fav);

Lastly, this should be Captain Obvious by now – We retrieve the string from the database, json_decode() to turn it back into an array.

 

 

USEFUL BITS & LINKS

That’s all for the main tutorial, and here is a small section on some extras and links that may be useful to you.

 

THE SUMMARY

PHP JSON Functions
Function Description Reference Link
json_encode() Turns an object or array into a JSON encoded string. Click Here
json_decode() Convert a JSON encoded string back into an object or array. Click Here
Javascript JSON Functions
Function Description Reference Link
JSON.stringify() Encodes an object or array into a JSON string. Click Here
JSON.parse() Decodes a JSON string, and turn it back into an object/array. Click Here

 

INFOGRAPHIC CHEATSHEET

Javascript PHP JSON Example (Click To Enlarge)

 

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!

Leave a Comment

Your email address will not be published. Required fields are marked *