Jump to: navigation, search

PHP JSON Access

From w3cyberlearnings

Contents

PHP Access JSON data

JSON data needs to converts to an array or an object before we can access them.

Example 1: JSON data and Object

  • Convert JSON data to object, and access object values.
<?php

$my_name = '{"age":30,"address":"huntsville"}';

$my_profile = json_decode($my_name);
echo "My age is: " . $my_profile->age .
 " address " . $my_profile->address;

?>

Output

My age is: 30 address huntsville

Example 2: JSON data and Associative array

  • Convert JSON data to an associative array and access an associative array values.
<?php

$my_json_data = '{
	      "name":"paul",
	      "age":28,
	      "address":"Houston, Tx",
	      "jobtitle":"php developer",
	      "hometown":"huntsville"}';

$my_arry_data = json_decode($my_json_data, 1);

foreach ($my_arry_data as $k => $v) {
     echo "{$k}=>{$v}<br/>";
}
?>

Output

name=>paul
age=>28
address=>Houston, Tx
jobtitle=>php developer
hometown=>huntsville

Example 3: JSON data and object

  • Convert JSON data to object and access object values.
<?php

$my_aj = '
	{
	       "person":
		[
			{"name":"paul","age":30,"address":"huntsville"},
			{"name":"david","age":40,"address":"grambling"},
			{"name":"king","age":10,"address":"austin"},
			{"name":"christ","age":31,"address":"dallas"},
			{"name":"yoko","age":53,"address":"japan"}
		],

		"country": 
		[
			 {"name": "japan"},
			 {"name": "cambodia"},
			 {"name":"china"},
			 {"name":"vietnam"}
       ]
					
	}';

// convert json to object
$my_obj = json_decode($my_aj);

echo $my_obj->person[0]->name;		// paul
echo "<br/>";

echo $my_obj->person[0]->age;			// 30
echo "<br/>";

echo $my_obj->person[2]->address ;  // austin
echo "<br/>";

echo $my_obj->country[0]->name ;		// japan
echo "<br/>";

echo $my_obj->country[1]->name ;		// cambodia
echo "<br/>";
echo "<br/>";

foreach ($my_obj->person as $ob) {
	echo "name: ". $ob->name.
	     " age: ". $ob->age . "<br/>";
}
?>

Output

paul
30
austin
japan
cambodia

name: paul age: 30
name: david age: 40
name: king age: 10
name: christ age: 31
name: yoko age: 53

Related Links


--PHP JSON Convert to Array-- PHP JSON Convert to Object-- PHP Access JSON Data--

Navigation
Web
SQL
MISC
References