Dbms Assignment 13
Dbms Assignment 13
Assignment No: 13
Class: T.E. Computer Roll No:
Objective:
1. To learn and understand JSON.
2. To implement encode & decode JSON objects using PHP.
Hardware requirements:
Any CPU with Pentium Processor or similar, 256 MB
RAM or more, 1 GB Hard Disk or more.
Software requirements:
Ubuntu 14.04 or Windows 7, PHP5.2, Any Javascript enabled browser.
Theory:
Environment
As of PHP 5.2.0, the JSON extension is bundled and compiled into PHP by
default.
JSON Functions
Function Libraries
Syntax
string json_encode ( $value [, $options = 0 ] )
Parameters
value − The value being encoded. This function only works with UTF-8 encoded
data.
Example
The following example shows how to convert an array into JSON with PHP −
<?php
$arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);
echo json_encode($arr);
?>
{"a":1,"b":2,"c":3,"d":4,"e":5}
The following example shows how the PHP objects can be converted into JSON
−
<?php
class Emp {
public $name = "";
public $hobbies = "";
public $birthdate = "";
}
$e = new Emp();
$e->name = "sachin";
$e->hobbies = "sports";
$e->birthdate = date('m/d/Y h:i:s a', "8/5/1974 12:20:03 p");
$e->birthdate = date('m/d/Y h:i:s a', strtotime("8/5/1974 12:20:03"));
echo json_encode($e);
?>
Syntax
mixed json_decode ($json [,$assoc = false [, $depth = 512 [, $options = 0 ]]])
Paramaters
json_string − It is an encoded string which must be UTF-8 encoded data.
assoc − It is a boolean type parameter, when set to TRUE, returned objects will
be converted into associative arrays.
Example
The following example shows how PHP can be used to decode JSON objects −
<?php
$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
var_dump(json_decode($json));
var_dump(json_decode($json, true));
?>
object(stdClass)#1 (5) {
["a"] => int(1)
["b"] => int(2)
["c"] => int(3)
["d"] => int(4)
["e"] => int(5)
}
array(5) {
["a"] => int(1)
["b"] => int(2)
["c"] => int(3)
["d"] => int(4)
["e"] => int(5)
}
Conclusion: Thus we learnt and successfully implemented encoding d& decoding of php
string , objects into JSON format and viceversa.