Using JSON with PHP


JSON is an excellent mean for data transfer over the http, it is getting more popularity day by day so here we present a little overview of how you can use JSON with PHP one of most popular combination on the web world these days.

Lately XML has been treated as a king for the purpose of data transmission across the web. But it has got some serious competetion as JSON. JSON, the Java Script Onject Notation is a simple and easy way for the data transmission. This is not only fast but easy also.

JSON is much simpler than xml you dont have to go through and parse the tags. then store in variables. JSON is in exect the way javascript object is defined and you can simply use it like this. the JSON string looks like this.

{
"prop1":val1,
"prop2":val2,
"prop3":val3,
"prop4":val4
};

php uses mainly two functions for the json encoding and decoding viz:
json_encode
json_decode
there are two more functions but not used widely. you can look up on php-json documentation here. And you can look at JSON documentation here. Now lets look at the tutorial, this will help you to understand the use of JSON with php.

Look at following program:


<style>
	body{
		width:95%;
		margin: 0 auto;
		border:1px solid #cccccc;
		margin:1%;
	}
</style>
<?php
	$init = array("a"=>1,"b"=>2,"c"=>3,"d"=>4,"e"=>5);
	echo "The Array Declared in php is";
?>
<pre>
	<?php print_r($init); ?>
</pre>
<?php
	$jsonencodedarray = json_encode($init);
	echo "json encoded array looks like this:<br/>";
	echo $jsonencodedarray;
	?>
<script>
	var obj = (<?php echo $jsonencodedarray; ?>);
	alert(obj.a);
	alert(obj.b);
	alert(obj.c);
	alert(obj.d);
	alert(obj.e);
</script>
<br/>
<br/>
<?php
	$decodedarray = json_decode($jsonencodedarray,true);
	echo "json decode returns the original array that we had:";
?>
<pre>
<?php print_r($decodedarray); ?>
</pre>

This code is a simplest demonstration fo the JSON use.
First of all I have created an associative array in php. then i encoded it into json form using. json_encode.


$init = array("a"=>1,"b"=>2,"c"=>3,"d"=>4,"e"=>5);
$jsonencodedarray = json_encode($init);

after this I have used this encoded string in javascript as object because the json encoded string is in the form of javascript object syntax.


var obj = ();

and finally to show the decoding i used json_decode this will reobtain the value from json format into the php array.


$decodedarray = json_decode($jsonencodedarray,true);

in json_encode takes the encoded json type string and passing another optional variable as true will return an associative array. This may be used in case the data is send using the ajax.

you can see the working demo here.

Well I hope this will help you in understanding the phenomenon of JSON.
Hope you enjoyed the reading, if you like it please share it.