Creating and Parsing JSON data with PHP

July 9, 2009 | In: php

Today, I’m going to tell you something about JSON data and how we can handle them via PHP. Although, JSON stands JavaScript Object Notation, it is used by many other technologies like PHP and Java for data interchange format over the Internet.

What is JSON?

JSON is ultra-weight data interchange data format used over the internet for transferring the data. While XML is a dominant data interchange format over the internet but JSON is less complex and light-weight data.

Though it was first made to be used with JavaScript for accessing remote data, it is now used by many other languages because JSON data is platform independent data format.

Data Types and Example of JSON data

JSON supports various kind of data types which included numbers, strings, booleans as well as array datas and obviously object (collection of key:value pairs, comma-separated and enclosed in curly brackets).

Now, let’s look at the example of simple format of JSON data for a detail of a employee,


Creating and Parsing JSON data format in PHP

To handle JSON data there is JSON extension in PHP which is aviable after PHP 5.2.0. Two funcitons : json_encode() and json_decode() are very useful converting and parsing JSON data through PHP.

First of all, let’s look at the PHP code to create the JSON data format of above example using array of PHP.

$json_data = array ('id'=>1,'name'=>"mike",'country'=>'usa',"office"=>array("microsoft","oracle"));
echo json_encode($json_data);

The above code generates the JSON data exactly as above. Now, let’s decode above JSON data in PHP.

$json_string='{"id":1,"name":"mike","country":"usa","office":["microsoft","oracle"]} ';

Now, the $obj variable contains JSON data parsed in PHP object which you can display using code below.

echo $obj->name; //displays mike
echo $obj->office[0]; //displays microsoft

As you can guess,$obj->office is an array and you can loop through it using foreach loop of PHP,

foreach($obj->office as $val)
    echo $val;