In this lesson, you will learn how to use JSON with PHP for web development.

What is JSON?

JSON is a short form of JavaScript Object Notation. It is not a programming language itself; it is merely a data format which is used to exchange data between a server and a web browser. Now you must be wondering what may be only JavaScript can interact with JSON. The format was designed to structure data in a simple and organized way. Wide range of languages including PHP can easily communicate with the format and use as an alternative to XML.

A simple example of JSON

var json_string = {
"pizza_name":"Fajita",
"pizza_toppings":"Tomato, Pepperoni, Mushrooms,Onions",
"Pizza_size":"medium"
}
console.log(json_string.pizza_name);

Now copy and paste the above code in a new file and save as “pizza.json.”
The JSON data is consist of key: value pair. {“key”: “value”}. As you can see the data is enclosed with the curly brackets which resemble like JavaScript object.
You can also save JSON text as an array which means the following example is also a valid JSON.

var json_arr =[{"color":"red", "hexcode":"FF0000"},
{"color":"violet", "hexcode":"EE82EE"},
{"color":"Blue", "hexcode":"00000FF"}
];

Access data and its value in JSON

Use the code below to access the data and its value:

console.log(json_arr[0].color);

JSON is structured data; therefore, it doesn’t support comments. If you still have to include comments, then add these as data as well. You could have data called comments.

var json_comment ={"comments": "your comments goes here"};
console.log(json_comment.comments);

The JSON format is simple and widely used format nowadays as it is lightweight and supported by many languages.
In JavaScript:

var x1 = {x:4, y:5};
console.log(typeof x1); // is an object type

whereas

var x2 = '{"x":"4", "y":"5"}';
console.log(typeof x2); // is a JS string

Now let’s say you have a JS string, you have to convert it into JS object, then you have to parse it like

var obj = JSON.parse(x2);
console.log(typeof obj); // is an object type.
console.log("value of x is " + obj.x); // value of x is 4.

Encoding JSON in PHP

Since PHP 5.2, the JSON encoding and decoding is a part of core PHP.
PHP function json_encode returns the JSON representation of value on success or Boolean value false on failure.

Syntax of Encoding JSON in PHP

json_encode ( mixed $value [, int $options = 0 [, int $depth = 512 ]] ) : string

Exampe of Encoding JSON in PHP

<?php
$arr = array ("msg" =>"hello");
$json_obj = json_encode($arr);
var_dump($json_obj);
?>

The output would be JS string

‘{“msg”:”hello”}’ (Length=15).

Tip: To process JSON data to a JavaScript program, it is advisable to include header(‘Content-Type: application/json’); at the top of the document.

Decoding JSON in PHP

PHP provides you with a json_decode() function that decodes a JSON string and converts into to JS object.

Syntax of Decoding JSON in PHP

json_decode ( string $json [, bool $assoc = FALSE [, int $depth = 512 [, int $options = 0 ]]] ) : mixed

Example of Decoding JSON in PHP

<?php
$json_obj = json_decode($json_string);
var_dump($json_obj);
?>

The output would be JS object.
object(stdClass)[1] public ‘msg’ => string ‘hello’ (length=5)

The json_decode() function returns null if the string passed to is not a valid JS string.
If you try to access a property of JS object, it will be something like this.
echo $json_obj->msg; // hello

AJAX, JSON, and PHP

Now, as we have a basic understanding of JSON, let’s move to a slightly more complex example.
You can request JSON data from the server using AJAX. If the response is valid JSON, you can parse the string into JS object using JSON.parse() function.
Create a file practice.json and copy paste the following code.

{
  "Movie_name": "Mission Impossible",
  "Production_studio": "Skydance Media",
  "Cast": [
    {
      "Male": "Tom Cruise",
      "character_name": "Ethan Hunt"
    },
    {
      "Supporting": "Simon Pegg",
      "character_name": "Benji Dunn"
    },
    {
      "Female": "Rebecca",
      "name": "ILsa Faust"
    }
  ]
}

Now create another file practice.php

<p id="demo"></p>

<script>
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var obj = JSON.parse(this.responseText);
var movie = "Movie Name = "+ obj.Movie_name+"<br>";
movie += "Production Studio = " +obj.Production_studio + "<br>";
movie += "Cast - Female = "+ obj.Cast[2].Female;

document.getElementById("demo").innerHTML = movie;

}
};
xmlhttp.open("GET", "practice.json", true);
xmlhttp.send();
</script>

The output would be:

JSON AJAX Sample

PHP Error Handling Tutorial Home PHP and OOP

 

Last modified: April 29, 2019