Asif18

{ 3 Comments }

Here we going to know about the JSON library in php. JSON is one of the client side scripting language used for send or get the large amount of data easily. It also known as light weight code. JSON is using in many popular sites such as google, Facebook etc. We can pass or save the data with out custom parameters. Below is a small example of json_encode() and json_decode()

Step 1: Create Json using PHP

<?php
$encode = array("userdetails" => array(array("name" => "mohamedasif", "age" => "18")), "workdetails" => array(array("company_name" => "My Company", "role" => "web application developer", "employees" => "91")));
$json_encode = json_encode($encode);
echo $json_encode."<br/>";
?>

From the above step we have created the JSON. By using simple array() we can easily create JSON in php. We can aslo add mpre custom parameters to save the value. To check that created JSON is valid or not we need to compile the parameters and values. by using this http://jsonlint.com/ we can validate our JSON.

Step 2 : Decode the JSON

From the above generated JSON we can decode it by using json_decode(). Below is a small example for decode json using php.

<?php
/* create JSON from the first 1*/
$encode = array("userdetails" => array(array("name" => "mohamedasif", "age" => "18")), "workdetails" => array(array("company_name" => "My Company", "role" => "web application developer", "employees" => "91")));
$json_encode = json_encode($encode);
echo $json_encode."<br/>";

$obj = json_decode($json_encode); // this is the function used to decode the generated JSON

/* decode the generated JSON from the first 2 */
foreach($obj->userdetails as $udetails){
	echo $udetails->name;
	echo "<br/>";
	echo $udetails->age;
	echo "<br/>";
}
foreach($obj->workdetails as $wdetails){
	echo $wdetails->company_name;
	echo "<br/>";
	echo $wdetails->age;
	echo "<br/>";
}
?>

By using json_decode() we can decode the generated JSON. It can be saved as an object. Is the JSON contains child elements like in above example means we need to split the object and loop it. If the generated json contains only single parameters means no need to loop. First we need to save the generated JSON in an object by using json_decode(). After that we need to create a foreach loop to loop a single variable and get that inner values like in above example. Thus the JSON will work. Its a light weight code and also an effective one. we can save the data in MySql as JSON format for reliable methods of data fetching.

Comments (3)