08 February 2017

Using JSON inside PHP


JSON (JavaScript Object Notation) allows to pass data between server and web application similar to XML .
PHP: Hypertext Preprocessor , is ueed for creating dynamic web pages. It can be used inside HTML as input and the output can be in HTML too.

PHP has two functions to handle JSON objects.
1) json_decode( )
    It takes a JSON encoded string input , and returns into PHP variable

2) json_encode( )
    It takes PHP variable and return JSON representation of the value

There is another function useful in case of debugging :
    json_last_error()
    It returns the last error due to recent JSON parsing.
   
Example #1 (php code) use of json_encode()
<?php
$arr = array ('a'=>1,'b'=>2,'c'=>3,'d'=>4,'e'=>5);

echo json_encode($arr);
?>
Output:
{"a":1,"b":2,"c":3,"d":4,"e":5}

Example #2 (php code) using json_decode()

<?php
$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';

var_dump(json_decode($json));
var_dump(json_decode($json, true));

?>
Output :
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)
}

(If you found this article useful then share with your friends.)

No comments: