How to parse JSON
Pre-requisites: Basic Understanding HTML and JQuery.
In this project:
- We will use
json_encode()
andjson_decode()
functions to parseJSON
data.
parseJSON.php
file:
<?php
// JSON ENCODE
$indexedArr = array("Asia", "Africa", "Australia", "Europe", "Antartica");
echo "Index Array JSON <br>";
echo json_encode($indexedArr);
echo "<br></br>";
echo "Associative Array JSON <br>";
$associativeArr = array("Smith" => 92, "Chris" => 80, "John" => 95, "Steve" => 96);
echo json_encode($associativeArr);
echo "<br><br>";
// JSON DECODE
$json = '{"Smith":92,"Chris":80,"John":95,"Steve":96}';
$outputArr = json_decode($json);
echo "<table border='1' cellpadding='6' cellspacing='0'>
<tr>
<th>Name</th>
<th>Marks</th>
</tr>";
foreach($outputArr as $name => $marks){
echo "<tr>";
echo "<td>".$name."</td>";
echo "<td>".$marks."</td>";
echo "</tr>";
}
echo "</table>";
?>
Run parseJSON.php
file in your browser to get the following output. URL may look like as follows:
Code Explanation of
|
||
1. |
|
Declaring and initializing an indexed array. |
2. |
|
|
3. |
|
|
Summary
In this project, we have learned to parse a PHP array into a JSON string using json_encode
function.
We have also learned to parse JSON string to a PHP array using json_decode
function. This is how, we exchange data in a standard format.
It is a language independent data format, therefore it can be easily used with other programming languages as well.