Introduction to JSON with PHP

PHP JSONWhat is JSON, and what can it do? In this tutorial you learn how to use JSON to easily move data around the web. You also look at how to work with JSON using both JavaScript and PHP. If you’ve developed websites or web apps at all, you’ve probably heard of JSON, at least in passing. But what exactly is JSON? What can it do, and how do you use it? In this tutorial you’ll learn the basics of JSON.

You’ll look at the following topics:

  • What JSON does
  • The kinds of things JSON is used for
  • How to create JSON strings
  • A simple JSON example
  • How JSON compares to XML, and
  • How to work with JSON using both JavaScript and PHP.

Let’s get started!

What is JSON?

JSON is a simple, text-based way to store and transmit structured data. By using a simple syntax, you can easily store anything from a single number through to strings, arrays, and objects using nothing but a string of plain text. You can also nest arrays and objects, allowing you to create complex data structures.

Once you’ve created your JSON string, it’s easy to send it to another application or computer, because it’s just plain text.

JSON has a lot of advantages:

  • It’s compact
  • It’s easy for both computers and people to read and write
  • It maps very easily onto the data structures used by most programming languages (numbers, strings, booleans, nulls, arrays and associative arrays)
  • Nearly all programming languages contain functions or libraries that can read and write JSON structures

Note:

JSON stands for JavaScript Object Notation. As the name implies, it’s based on the way you define objects (which are very similar to what you’d call associative arrays or hashes in other languages), and arrays.

How does it work?

JSON is capable of setting up data constructs for integers, strings, arrays, and booleans – the most essential data building blocks. Using a carefully defined syntactical construct, JSON can be used to outline an object and with the use of javascript’s eval() function, they can be converted to a working object.

But the power does not end there. Other popular programming languages have been implementing native support for JSON, such as PHP and ActionScript. For example, PHP can now convert an associative array of data into a JSON string by using the new json_encode() function, provided in version 5.2+ of the language. For languages without native support, you can find a full range of implementation classes available at the JSON website.

How to write JSON Syntax:

Declaration

All JSON objects are declared with a pair of curly braces. You can assign them to a variable like you would any other data structure.

var myObj = {}

That’s it! While not very powerful, this is all that’s required to create objects using JSON. So let’s start adding some properties to this object.

Strings

We are going make this object represent me, so let’s start by adding my name.

var myObj = {name: 'Nahid'}

Let’s take a second to carefully look at what we did here. We wanted to add a property called “name”, and to do so, you simply write the property, “name”. We follow the property label by a colon to separate the property name and its value. To the right of the colon, comes the value. Since we wanted the value to be a string, we put it in quotes.

With the JSON we have put in place, you are now able to access the property by using the dot notation. To access a property, follow the “Variable [dot] property” construct.

alert(myObj.name) // "Nahid"

Integers

If we wanted to assign a property to the object of an integer data type, there is no need to quote the value.

var myObj = {age: 24}

Multiple properties are separated by a comma.

var myObj = {name: 'Nahid', age: 24}

alert("My name is " + myObj.name + " and I'm " + myObj.age);

// "My name is Nahid and I'm 24

Booleans

Like integers, booleans are also unquoted

var myObj = {name: 'Nahid', age: 24, engaged: true}

Arrays

Arrays can contain a collection of the previously mentioned data types. To define an array, wrap the value in square brackets and separate the values with commas.

Note: I will now add line breaks and indentation for legibility. It has no bearing on the working order of the object.

var myObj = {

name: 'Nahid',

age: 24,

engaged: true,

favorite_tv_shows: ['Lost', 'Dirty Jobs', 'Deadliest Catch', 'Man vs Wild']

}

You can access a value in an array in the object by using a combination of the dot notation (to access the objects property) and index notation (to access an indexed value of an array).

alert(myObj.favorite_tv_shows[1]); // "Dirty Jobs"

To take the array complexity one step further, an array can also contain other objects.

var myObj = {

name: 'Nahid',

age: 24,

engaged: true,

favorite_tv_shows: ['Lost', 'Dirty Jobs', 'Deadliest Catch', 'Man vs Wild'],

family_members: [

{name: "Nahid", age: 27, relation: "father"},

{name: "Tina", age: 24, relation: "sister"}

]

}

This still requires dot and index notation, with an additional dot notation for accessing the property of the object found in the indexed array value.

alert(myObj.family_members[1].name) // "Tina"

There is one situation where you will use square brackets to access an objects property and not the dot notation: when you are using a variable as the property name. For example:

var myObj = {

name: 'Nahid',

age: 27,

engaged: true,

favorite_tv_shows: ['Lost', 'Dirty Jobs', 'Deadliest Catch', 'Man vs Wild'],

family_members: [

{name: "Nahid", age: 57, relation: "father"},

{name: "Tina", age: 26, relation: "sister"}

]

}

var property = "age"

alert(myObj[property]); // "24"

Recap

Take some time experimenting with JSON and you will see that you can pick up the concept and syntax rather quickly. As a caveat that may save you time in the future: certain languages require you to quote the property names, such as ActionScript. If not, it will complain.

myObj = {name: "Nahid"} // will complain

myObj = {"name": "Nahid"} // will work</pre>

Creating Object in JavaScript using JSON

We can create objects in JSON with JavaScript in many ways :

  1. “var JSONObjectName ={};” will create an empty object.
  2. “var JSONObjectName= new Object();” will create a new Object.
  3. “var JSONObjectName = { “name “:”Fahad”, “age”:23}; will create an Object with attribute name which contains value in String and age with numeric value.

Now by creating this object we can access attributes by only “.” operator.

Here is the full example code for creating an Object in JavaScript using JSON:
ObjectJavaScript-JSON.htm

<html>
<head>
<title>
 Object creation in JSON in JavaScript
</title>
<script language="javascript" >
var JSONObject = {  "name" : "Fahad",
  "address"  : "420 Hatirpool",
  "age"  : 23,
   "phone"   : "011-4565763",
   "MobileNo"  : 0981100092
  };
document.write("<h2><font color='blue'>Name</font>::"
   +JSONObject.name+"</h2>");
document.write("<h2><font color='blue'>Address</font>::"
   +JSONObject.address+"</h2>");
document.write("<h2><font color='blue'>Age</font>::"
   +JSONObject.age+"</h2>");
document.write("<h2><font color='blue'>Phone No.</font>::"
   +JSONObject.phone+"</h2>");
document.write("<h2><font color='blue'>Mobile No.</font>::"
   +JSONObject.MobileNo+"</h2>");
</script>
</head>
<body>
<h3>Example of object creation in JSON in JavaScript</h3>
</body>
</html>

Output:

Name::Fahad

Address::420 Hatirpool

Age::23

Phone No.::011-4565763

Mobile No.::981100092

Example of object creation in JSON in JavaScript

Creating Array Objects in JavaScript with JSON

In This example we have created an object “students” which contains two array objects “Maths” and “Science” containing name, marks and age of two students. Now we can access these objects value in the following way:

“students.Maths” for accessing Maths array and “students.Science” for accessing Science array object. Now to access first element of the Maths array we can write it as “students.Maths[1]” and then we can access elements of this array as “students.Maths[1].Name” for name and “students.Maths[1].Marks” for marks of the first student in Maths and so on.

Here is the full example code for JavaScript-JSONArray.htm file.

<html>
<head>
<title>
Array JSON-JavaScript Example
</title>
<script language="javascript" >
var students = { "Maths" : [

{"Name" : "Fahad", // First element
  "Marks" : 67,
 "age" : 23 },
{"Name"  : "Vimrul",  // Second element
 "Marks" : 65,
 "age" : 21 }
 ],
"Science" :  [
{"Name"  : "Mizan",  // First Element
 "Marks" : 56,
 "age" : 27 },
  {"Name"  : "Mithu",  // Second Element
  "Marks" : 78,
 "age" : 41 }
 ]
  }
  // Printing all array values
var i=0
document.writeln("<table border='1'><tr>");
for(i=0;i<students.Maths.length;i++)
{
  document.writeln("<td>");
  document.writeln("<table border='0'  width=100 >");
  document.writeln("<tr><td><B>Name</B></td><td width=50>"
  +students.Maths[i].Name+"</td></tr>");
  document.writeln("<tr><td><B>Marks</B></td><td width=50>"
  +students.Maths[i].Marks +"</td></tr>");
  document.writeln("<tr><td><B>Age</B></td><td width=50>"
  +students.Maths[i].age +"</td></tr>");
  document.writeln("</table>");
  document.writeln("</td>");
}
for(i=0;i<students.Science.length;i++)
{
  document.writeln("<td>");
  document.writeln("<table border='0'  width=100 >");
  document.writeln("<tr><td><B>Name</B></td><td width=50>"
   +students.Science[i].Name+"</td></tr>");
  document.writeln("<tr><td><B>Marks</B></td><td width=50>"
   +students.Science[i].Marks +"</td></tr>");
  document.writeln("<tr><td><B>Age</B></td><td width=50>"
   +students.Science[i].age +"</td></tr>");
  document.writeln("</table>");
  document.writeln("</td>");
}
document.writeln("</tr></table>");
</script>
</head>
<body>
Using Array of objects via JSON in JavaScript
</body>
</html>

Output:

javascript json example

How to create and read JSON strings in PHP

json with php

PHP, like JavaScript, has functions that can convert variables to JSON strings and vice-versa. Let’s take a look at them.

Creating a JSON string from a PHP variable

json_encode() takes a PHP variable and returns a JSON string representing the variable. Here’s our shopping cart example written in PHP:

<?php

$cart = array(

  "orderID" => 12345,

  "shopperName" => "Faisal Ahmed",

  "shopperEmail" => "[email protected]",

  "contents" => array(

    array(

      "productID" => 34,

      "productName" => "SuperWidget",

      "quantity" => 1

    ),

    array(

      "productID" => 56,

      "productName" => "WonderWidget",

      "quantity" => 3

    )

  ),

  "orderCompleted" => true

);

echo json_encode( $cart );

?>

This produces exactly the same output as our JavaScript example — a valid JSON string representing the variable’s contents:

Output:

{“orderID”:12345,”shopperName”:”Faisal Ahmed”,”shopperEmail”:”[email protected]”,”contents”:[{“productID”:34,”productName”:”SuperWidget”,”quantity”:1},{“productID”:56,”productName”:”WonderWidget”,”quantity”:3}],”orderCompleted”:true}In a real-world online store, your PHP script would send this JSON string as part of the Ajax response back to the browser, where the JavaScript code would use JSON.parse() to turn the string back into a variable so it can display the cart’s contents to the shopper.

Note: You can also pass various flags as a second argument to json_encode(). These let you do things like encode certain special characters using hex notation to make the string more portable, and force empty and indexed arrays to be encoded as objects (associative arrays). Find out more.

Creating a PHP variable from a JSON string

To go the other way and convert a JSON string into a PHP variable, you use — you guessed it — json_decode(). Let’s rewrite our JavaScript JSON.parse() example in PHP:

<?php

$jsonString = '

{

  "orderID": 12345,

  "shopperName": "Faisal Ahmed",

  "shopperEmail": "[email protected]",

  "contents": [

    {

      "productID": 34,

      "productName": "SuperWidget",

      "quantity": 1

    },

    {

      "productID": 56,

      "productName": "WonderWidget",

      "quantity": 3

    }

  ],

  "orderCompleted": true

}

';

$cart = json_decode( $jsonString );

echo $cart->shopperEmail . "<br>";

echo $cart->contents[1]->productName . "<br>";

?>

As with the JavaScript version, this produces the following output:

[email protected]
WonderWidget

By default, json_decode() returns JSON “objects” as actual PHP objects. These are generic PHP objects of the stdClass class. That’s why we used -> to access the objects’ properties in the example above.

If you’d rather return JSON objects as PHP associative arrays, just pass true as a second argument to json_decode(). For example:

$cart = json_decode( $jsonString, true );

echo $cart["shopperEmail"] . "<br>";

echo $cart["contents"][1]["productName"] . "<br>";
 

This displays the same output:
[email protected]
WonderWidget

Convert a PHP Class to JSON

As json_encode() is recursive, you can use it to serialize whole structure of objects.

</pre>
<?php

class A {

public $a = 1;

public $b = 2;

public $collection = array();

function __construct(){

for ( $i=3; $i>0; $i--){

array_push($this->collection, new B);

}

}

}

class B {

public $a = 1;

public $b = 2;

}
echo "<pre>";
echo json_encode(new A);

?>


Will give:

{

    "a":1,

    "b":2,

    "collection":[{

        "a":1,

        "b":2

    },{

        "a":1,

        "b":2

    },{

        "a":1,

        "b":2

    }]

}

Combining PHP, JSON and jQuery

Now I’ll show you how simple it is to make PHP communicate with a JSON data source using jQuery’s Ajax functionality.

Step 1:
First we’re going to create a form with a dynamic dropdown. The dropdown will show a list of cities that we retrieve from a JSON datasource.

Step 2:
Our first step is to create the script that sends the JSON data. We load up our editor. I’ve already created a few blank scripts here but we’ll fill these in as we go.

Step 3:
So json.php. We create an array. This is just a PHP array with a list of cities. Adelaide, Perth, Melbourne Sydney. And we can send back this in JSON format – which is basically just JavaScript code – using json_encode(). We just pass the array and save the script.

Step 4:
Now, back in Chrome we load the file (index.php). That’s the array we just created. If you actually look in developer tools, the script is here under resources. It’s sent it with content type text/html. Technically this isn’t really a problem. It will work, but to be correct it needs to be application/json content type.

Step 5:
So just back in json.php use the header() function, content-type and then save, reload. Now if we look here, it’s application/json and Chrome gives us a warning here, that’s just because we tried to display it as a normal HTML page even though it’s not.

Listing 1 The JSON data source (json.php)

<?php
    $cities = array(
        'Adelaide',
        'Perth',
        'Melbourne',
        'Sydney'
    );

    header('Content-type: application/json');
    echo json_encode($cities);
?>

Step 6:
That’s the data source done. Next we’re going to create some JavaScript to actually output that. Let’s go back here. The script we’ll just update now to load a select box. Now this doesn’t actually do anything, all we’re going to do is populate this. So let’s call it city, and give it an id of #city-list, so we can refer to it later in our JavaScript. And we’ll just put a blank element that instructs the user to select a city. And we save that, and then go back to the index.php script.

Step 7:

Now we’ve got this dropdown which we’ll populate shortly. We’re using jQuery in this. To make things a little bit simpler we’re going to use Google’s hosted version of jQuery. We can search Google jQuery and I think it’s the first link. So we just click on jQuery and it shows you the versions that they host. You can either use their loader or just go straight to the path. We’ll get the minified version (jquery.min.js) because it loads quicker. We don’t need the full source code.

Step 8:

So let’s just load that here. So that’s all we need to do to import jQuery into our script, and we’re about to create this script.js file, so we’ll just load that one as well.
The main index file that displays the form (index.php)

<html>
    <head>
        <title>JSON Example - w3programmers.com</title>
        <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
        <script type="text/javascript" src="script.js"></script>
    </head>
    <body>
        <div>
            <h1>PHP + jQuery Example - PhpRiot.com</h1>
             <select name="city" id="city-list">
                <option value="">Select a city...</option>
            </select>
        </div>
    </body>
</html>

Step 8:
Okay so that’s now loading, it doesn’t actually do anything yet, but what we can do is just ensure that jQuery is loaded. So this is the “on dom loaded” event. Save that one and go back to the browser. We don’t need this any more, now refresh. Hopefully we’ll get an alert box just to ensure that jQuery is loaded, and there we go. That means we can keep going.

Step 9:
Now, we go back, we can remove this alert. Now what we want to do is use the jQuery getJSON() function. So for that, we call $.getJSON(). The script is called json.php, so put that in, and the callback is the second argument, and when the callback is called the data returned from the script is passed as the first argument.

Step 10:
So that’s our placeholder. You can have a look at that before we do anything with it. Just throw in a console.log(), pass the data, save and return the Chrome. Now if you load developer tools. Let’s refresh this page. So now you can see this script here after the JavaScript is loaded it performed the JSON query. So that’s what we created earlier on but you can this output that we wrote to the console. So we’re most of the way there, all we need to do now is use this data to populate the select box.

Step 11:

So returning to our editor. So we just call $.each(), pass the array as the first argument and the callback as the second. The first argument to the callback is the index, so 0, 1, 2, 3 in this case, and the second argument is the value, which is the name of the city, which is what we’re going to use.

Step 12:

For each iteration of this loop we’re going to write a new option to the select box. So first we need to get the select box. So we’re going to call it var select, and we called that #city-list, and then in each iteration option, create the new option, so we set the value attribute, so when the form is submitted the value is passed in, and we set the HTML using the .html() function, so we just pass the city name again. And finally we append it to the select, so appendTo(select).

JavaScript to populate the select box with JSON (script.js)

jQuery(function($) {
        $.getJSON('json.php', function(json) {
                var select = $('#city-list');
                 $.each(json, function(k, v) {
                        var option = $('<option />');
                         option.attr('value', v)
                              .html(v)
                              .appendTo(select);
                });
        });
});

Final:
Now we can save, return to Chrome, and refresh. Now we’ve got our developer tools still open so you can see they’re all appearing here, and in the dropdown. And that’s all there is to it! Now we haven’t actually done anything with this list, but you can use this inside your normal forms, or you can trigger the load after a particular btuton is pressed. Here we’ve just made it simple and doing it onload, but you can really do it however you need to.

Combining PHP, JSON, MySQL and jQuery

  1. json-jquery.js – js file to request the data
  2. json-data.php – php file to connect to database to retrieve data
  3. page.html – html page to call/display data

json-jquery.js

$(document).ready(function(){

    //attach a jQuery live event to the button

    $('#getdata-button').live('click', function(){

        $.getJSON('json-data.php', function(data) {

            //alert(data); //uncomment this for debug

            //alert (data.item1+" "+data.item2+" "+data.item3); //further debug

            $('#showdata').html("<p>item1="+data.item1+" item2="+data.item2+" item3="+data.item3+"</p>");

        });

    });

});

json-data.php

<?php

//request data from the database

//code here to connect to database and get the data you want

/* Example JSON format

{

  "item1": "I love PHP and JSON",

  "item2": "You love PHP and JSON",

  "item3": "We love PHP and JSON"

}

*/

//return in JSON format

echo "{";

echo "item1: ", json_encode($item1), "\n";

echo "item2: ", json_encode($item2), "\n";

echo "item3: ", json_encode($item3), "\n";

echo "}";

?>

Alternative methods

Create an array in PHP and use the json_encode() function to encode the whole array.

<?php

$arr = array ('item1'=>"I love jquery4u",'item2'=>"You love jQuery4u",'item3'=>"We love jQuery4u");

echo json_encode($arr);

?>

This will output the array in the correct JSON format; however it may not include line breaks as the previous example shows so make sure you check this by alerting the data. There is also a json_decode() function which does the opposite.

page.html

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" " http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd ">

<html xmlns=" http://www.w3.org/1999/xhtml ">

<head>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

<title>Request json test</title>

<script src="http://code.jquery.com/jquery-1.5.js"></script>

<script src="json-jquery.js" type="text/javascript"></script>

</head>

<body>

<a href="#" id="getdata-button">Get JSON Data</a>

<div id="showdata"></div>

</body>

</html>
Hi, My name is Masud Alam, love to work with Open Source Technologies, living in Dhaka, Bangladesh. I graduated in 2009 with a bachelor’s degree in Engineering from State University Of Bangladesh, I’m also a Certified Engineer on ZEND PHP 5.3, I served my first five years a number of leadership positions at Winux Soft Ltd, SSL Wireless Ltd, CIDA and MAX Group where I worked on ERP software and web development., but now i’m a co-founder and Chief Executive Officer and Managing Director of TechBeeo Software Consultancy Services Ltd. I’m also a Course Instructor of ZCPE PHP 7 Certification and professional web development course at w3programmers Training Institute – a leading Training Institute in the country.
One comment on “Introduction to JSON with PHP

Leave a Reply

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