Parsing/Building JSON in PHP

Example for building/parsing JSON in PHP

Below example index.html.

Building JSON Object in Javascript:


					
<?php
$myPhpObj = new stdClass();
$myPhpObj->names = "testjsonuser ";
$myPhpObj->actions = "IllustrateJSONObjectInScript";
$myPhpObj->logincount  = 2;

$jsonObject = json_encode($myPhpObj);

echo "JSON Object: ";
echo $jsonObject;
?>
					
					

Result:

JSON Object: {"names":"testjsonuser","actions":"IllustrateJSONObjectInScript","logincount":2}

We could see the result displays the JSON Object., and it has string field printed with double quotes.
The PHP Object is created with only name value pairs in jsonObject field. Then the PHP object is converted to JSON Object.,

Parsing JSON Object to PHP

						
<?php
$myPhpObj = new stdClass();
$myPhpObj->names = "testjsonuser ";
$myPhpObj->actions = "IllustrateJSONObjectInScript";
$myPhpObj->logincount  = 2;

$jsonObject = json_encode($myPhpObj);

echo "PHP Object: ";

$phpObject = json_decode($jsonObject);
echo "names:" . $phpObject->names . ",";
echo "actions:" . $phpObject->actions. ",";
echo "logincount:" . $phpObject->logincount;

?>
						
					

Result:

PHP Object: names:testjsonuser ,actions:IllustrateJSONObjectInScript,logincount:2

The JSON Object created can be parsed using the field name present in JSON Object.
The "names", "actions" and "logincount" values is displayed by parsing the PHP Object formed using JSON Object.