How to use JSON data in PHP

Now a day almost APIs and web services are using JSON format for transfer and represent data instead of XML. Due to JSON is easy to understood and faster then XML. JSON is language independent there for used by many languages, PHP is one of them.
For using JSON in PHP we need to use two predefined functions:

  • json_decode()
  • json_encode()

Convert to JSON
json_encode() returns the JSON representation of a value. we can convert any data to JSON by using this function but array is commonly used. It will returns a JSON encoded string on success or False on failure.

<?php
	$data = array(
				"code" => 101,
				"title" => "Some text"
			);
	echo json_encode($data);
?>

In above snippet i am echo it’s value but you can also assign it to variables. It will output:

{"code":101,"title":"Some text"}

Using JSON
json_encode() Takes a JSON encoded string and converts it into a PHP variable. For this we need to pass string contains JSON data as a parameter. For illegal JSON string it will return NULL therefor check it before using JSON data.

<?php
	$json_str = '{"code":101,"title":"Some text"}';
	$obj = json_decode($json_str);
	echo "Code: " .	$obj->code;
	echo "Title:" . $obj->title;
?>

Leave a Reply

Your email address will not be published. Required fields are marked *