The following example demonstrates how to convert PHP objects into JSON format data
<?php
class Emp {
public $name = "";
public $hobbies = "";
public $birthdate = "";
}
$e = new Emp();
$e->name = "sachin";
$e->hobbies = "sports";
$e->birthdate = date('Y-m-d h:i:s a', "2016/9/19 12:20:03 p");
$e->birthdate = date('Y-m-d h:i:s a', strtotime("2016/9/19 12:20:03"));
echo json_encode($e);
?>
Program running results:
{"name":"sachin","hobbies":"sports","birthdate":"2016-09-19 12:20:03 pm"}
$json [,$assoc = false [, $depth = 512 [, $options = 0 ]]]
json_decode
json_decode() function is used to decode JSON format strings and convert them into PHP variables.
Syntax
json_decode ($json [,$assoc = false [, $depth = 512 [, $ options = 0 ]]])
Parameters
##· json_string: to be decoded JSON string, must be UTF-8 encoded data
· assoc: When this parameter is TRUE, an array will be returned, and when FALSE, an object will be returned.
· depth: Integer type parameter, which specifies the recursion depth
· options: Binary mask, currently only JSON_BIGINT_AS_STRING is supported.
json_decode() common Error
The following three ways of writing json are all wrong. Can you see where the error is? $bad_json = "{ 'bar': 'baz' }";$bad_json = '{ bar: "baz" }';
$bad_json = '{ "bar": "baz", }';
Executing json_decode() on these three strings will return null and report an error.
The first mistake is that the json delimiter (delimiter) only allows the use of double quotes, not single quotes.
The second mistake is that the "name" (the part to the left of the colon) of the json name-value pair must use double quotes under any circumstances.
The third error is that you cannot add a comma (trailing comma) after the last value.
In addition, json can only be used to represent objects and arrays. If json_decode() is used on a string or value, null will be returned.
Example
The following example demonstrates How to decode JSON data:
<?php
$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
var_dump(json_decode($json));
var_dump(json_decode($json, true));
?>
Program execution result:
##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)}
##Next Section
<?php
$arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);
echo json_encode($arr);
?>