We use cookies to improve our services and provide a better experience. By continuing to use this site, you agree with our Cookies Policy.

More than 400 step-by-step articles to guide you through online project development.
HomeTutorialsHosting ServicesCloud Servers

Introduction to JSON and PHP

JSON (JavaScript Object Notation) is a data exchange format that is both compact as is also easy to read (similar XML, but without as much additional markup). The syntax itself is a subset of JavaScript. Another positive feature of JSON is that you can work directly in JavaScript with its objects, so it is the perfect adhesive between server and client. Since unnecessary characters (overhead) are kept low, less of it needs to be transmitted and therefore saves bandwidth. In most modern web applications JSON has already overtaken XML, except probably in the Java world.

An Introduction to JSON

Since JSON is a subset of JavaScript, it shares all language constructs with its parent. In JSON, key / value combinations can be either arranged in arrays or be randomly stored in objects.

What data types are supported by JSON? Simply put, there are strings, numbers, booleans and NULL. Furthermore, arrays and objects can be used as values. Here’s a typical JSON document:

  "name": "Fred",
  "age": 40,
  "job": null,
  "married": true,
  "children": [
      "name": "Kate",
      "age": "13"
      "name": "Lilly",
      "age": "8"

This document contains almost all possible data types that can be expressed in JSON. There are no date objects or regular expressions. Furthermore, it must be ensured that the entire JSON document is encoded in UTF-8.

Since PHP allows more complex data types than JSON, some sort of conversion must take place. For example, when date properties are to be converted, you have to decide whether it is sufficient enough to store it as Unix timestamp or as a formatted string.

JSON encoding in PHP

Generally, PHP version 5.2 has JSON support but it is always advised to use version 5.4 or higher for full JSON integration.

With json_encode() all data types can be converted to JSON (except resources), provided they are encoded using UTF-8. “Classic” arrays (those with ascending numerical index) are converted into JSON arrays (square brackets). All other array types (especially associative arrays) are converted into objects.

The function call is simple and looks like this:

json_encode(mixed $value, int $options = 0);

A numeric value instead of an array as an argument for options seems unusual at first glance. In fact, it involves the – mainly common in C – language construct called bit mask . However, since they affect the way the encoding works, we just give it no parameter.

json_encode(array("apples" => true, "bananas" => null));
// Returns: {"apples":true,"bananas":null}

As the array in PHP is converted it relies on the indices used. You can see that json_encode() uses the data types so that boolean values or NULL are not converted to a string.

Now for the objects:

$user->firstname = "Jon";
$user->lastname = "Doe";
// Returns: {"firstname":"Jon","lastname":"Doe"}
$user->birthdate = new DateTime();
/* Returns:
  "firstname": "Jon",
  "lastname": "Doe",
  "birthdate": {
    "date": "2016-09-09 10:45:15",
    "timezone_type": 2,
    "timezone": "Europe/Vilnius"

The objects are analyzed and all visible (“public”) attributes are used for the conversion. This happens recursively so that the attributes of the above example DateTime object converts. This is an easy way to transfer date objects as JSON without having to deal much with the conversion.

JSON decode in PHP

Decoding is as easy as encoding function json_decode(). Here is a short example:

$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
var_dump(json_decode($json, true));

The above example will output:

array(5) {
    ["a"] => int(1)
    ["b"] => int(2)
    ["c"] => int(3)
    ["d"] => int(4)
    ["e"] => int(5)

If a potentially deep nested JSON document is decoded, one can with the limit to set a maximum argument count.


JSON is a compact and easy to read format for exchanging data between endpoints. It seems as if it would overcome XML as the de facto standard in Web applications very soon. PHP provides all the necessary tools to deal with JSON effectively and has numerous options to further handle data.

Rate this Tutorial:
No CommentsLeave a Comment