JSON in PHP


JSON is for javascript object nodes. JSON is a standard lightweight data-interchange format that is quick and easy to parser and generates.

Like XML, JSON is a text-based format that is easy to write and easy to understand for both humans and computers, but unlike XML, JSN data structures have captured less bandwidth compared to their XML versions. JSON is based on two basic structures:

Object: It is defined as a collection of key / value pairs (such as: value). Each object starts with a left curly bracket (and ends with a right curly bracket). Multiple key / value pairs are separated with commas.

Array: These values ​​are defined as an order list. An array starts with a left bracket [and ends with a bracket on the right]. Values ​​are divided by commas.



Syntax - 

{
"book": {
"name": "Harry Potter and the Goblet of Fire",
"author": "J. K. Rowling",
"year": 2000,
"genre": "Fantasy Fiction",
"bestseller": true
}
}


Example -

<?php
// Assign JSON encoded string to a PHP variable
$json = '{"Peter":65,"Harry":80,"John":78,"Clark":90}';

// Decode JSON data to PHP associative array
$arr = json_decode($json, true);
// Access values from the associative array
echo $arr["Peter"]; // Output: 65
echo $arr["Harry"]; // Output: 80
echo $arr["John"]; // Output: 78
echo $arr["Clark"]; // Output: 90

// Decode JSON data to PHP object
$obj = json_decode($json);
// Access values from the returned object
echo $obj->Peter; // Output: 65
echo $obj->Harry; // Output: 80
echo $obj->John; // Output: 78
echo $obj->Clark; // Output: 90
?>


Example -

<?php
// Assign JSON encoded string to a PHP variable
$json = '{"Peter":65,"Harry":80,"John":78,"Clark":90}';

// Decode JSON data to PHP associative array
$arr = json_decode($json, true);

// Loop through the associative array
foreach($arr as $key=>$value){
echo $key . "=>" . $value . "<br>";
}
echo "<hr>";
// Decode JSON data to PHP object
$obj = json_decode($json);

// Loop through the object
foreach($obj as $key=>$value){
echo $key . "=>" . $value . "<br>";
}
?>
Share on Google Plus

About It E Research

This is a short description in the author block about the author. You edit it by entering text in the "Biographical Info" field in the user admin panel.
    Blogger Comment
    Facebook Comment

0 comments:

Post a Comment