PHP Exercise : PHP Json Encode

Write a php program to loop over the json data.

Suppose, you have the following json data.


[
	{
	"name" : "John Garg",
	"age"  : "15",
	"school" : "Ahlcon Public school"
	},
	{
	"name" : "Smith Soy",
	"age"  : "16",
	"school" : "St. Marie school"
	},
	{
	"name" : "Charle Rena",
	"age"  : "16",
	"school" : "St. Columba school"
	}
]

Solution

PHP allows us to easily convert JSON to arrays. PHP provides predefined functions to easily encode and decode json string into php array. The following program converts the json string into array and loop over them.

<!Doctype>
<html>
 <head>
	<title>PHP Json Encode</title>
 </head>
 <body>
	<table>
	<tr>
		<td><b>Name</b></td>
		<td><b>Age</b></td>
		<td><b>School</b></td>
	</tr>
	<?php
	$student_json = '[
			{
				"name" : "John Garg",
				"age"  : "15",
				"school" : "Ahlcon Public school"
				},
				{
				"name" : "Smith Soy",
				"age"  : "16",
				"school" : "St. Marie school"
				},
				{
				"name" : "Charle Rena",
				"age"  : "16",
				"school" : "St. Columba school"
				}
			]';
	$students = json_decode($student_json, true);
	foreach($students as $student) {
	?>
	<tr>
		<td><?php echo $student->name; ?></td>
		<td><?php echo $student->age; ?></td>
		<td><?php echo $student->school; ?></td>
	</tr>
	<?php	
		}
	?>
	</table>
 </body>
</html>

Output of the above code

Name Age School
John Garg 15 Ahlcon Public school
Smith Soy 16 St. Marie school
Charle Rena 16 St. Columba school




Related PHP Programs for Practice

PHP - Division table program
PHP - Prime Number Program
PHP - Print numbers 10 to 1 using recursion
PHP - Loop through an associative array
PHP - Differentiate between fgets, fgetss and fgetcsv
PHP - Set session on login
PHP - Convert text to speech
PHP - Copying or moving a file
PHP - Locking a file
PHP - CURL Cookie Jar
PHP - Password Hashing
PHP - Emoji Unicode Characters PHP - Age calculator
PHP - Get array key
PHP - Capitalize first letter
PHP - Set Timezone
PHP - Remove duplicates from array
PHP - Calculate percentage of total
PHP - Fibonacci Series Program
PHP - Lock a file
PHP - Insert image in database




Read more articles


General Knowledge



Learn Popular Language