json_decode() | How To Convert JSON data to PHP’s Object in PHP

Date Published: 24/03/2020 Published By: JaiSchool

In this tutorial, you are going to know, how to process JSON (Javascript Object Notation) data in PHP.

The function json_decode() is used to convert the JSON object into PHP's object. The json_decode() is a function of PHP that decodes JSON object into PHP object.

To change the JSON data in an object of PHP, keep JSON data in a variable as a string. If JSON data is surrounded by a double quote then keep the JSON object as a string by surrounding it with a single quote otherwise use a double quote.

$json_data = '{
		"name":"Jaischool",
		"city":"Sikar",
		"state":"Rajasthan",
		"country":"India"
	     }';

And now, you need to make use of the json_decode() method to transform it into PHP's object.

In the argument of the json_decode(), pass the variable name in which you have stored the JSON data to process in PHP.

$php_obj = json_decode($json_data);

$php_obj is now an object of PHP, so for printing any property from it use object operator symbol and give property name after it.

echo $php_obj->name;

json_decode() function's code example

<?php

$json_data = '{
				"name":"Jaischool",
				"city":"Sikar",
				"state":"Rajasthan",
				"country":"India"
		}';

	$php_obj = json_decode($json_data);
	echo $php_obj->country;
?>

Publish A Comment

Leave a Reply

Your email address will not be published.