Saturday, December 28, 2013

Using JSON in PHP

JSON (JavaScript Object Notation) is a standard format used to transmit data between a server and a web application. It is an alternative to XML. JSON string is a human-readable text consisting of attribute-value pairs. JSON is a language-independent data format and many languages support generating and parsing JSON data.

The following is the format of the JSON string:
{
                “first_name” : “Barack”,
                “last_name” : “Obama”,
                “address” :{
                                “city” : “Washington, DC”,
                                “country” : “United States of America”
},
“phone_numbers” : [
{
                “type” : ”home”,
                “number” : ”000 000-0000”
},
{
                “type” : ”office”,
                “number” : ”000 000-1111”
}
                ]
}

PHP 5.2.0 supports JSON by default and we do not need any additional installation and configuration to use JSON. If the PHP version is less than 5.2.0, we need to install JSON PECL extension and guide for installation of PECL extensions can be found at the official PHP website php.net.
There are three functions in PHP to support JSON. They are json_encode, json_decode, and json_last_error. json_decode function converts JSON string into PHP variable to use that data for further programming.  If the JSON string cannot be decoded then null will be returned.

PHP json_encode() function coverts a PHP value into a JSON string. For example, from a PHP array, it can create a JSON representation of that array.

The following is the simple PHP script that uses JSON:
<?php
//Array creation
$arr=array('PHP','MySQL','Javascript');
//Encoding the array to JSON string
$json=json_encode($arr);
echo $json;
//Decoding the JSON string back to array.
$decode=json_decode($json);
echo "<br>";
echo $decode[0];

?>

No comments :

Post a Comment