JSON php

How to Parse JSON in PHP

The full form of JSON is JavaScript Object Notation. It is a text-based format of data like XML which is very easy to write and interpret by computers and human beings. It requires less bandwidth compared to XML. So, it is considered a lightweight data-interchange format which can be parsed and generated easily and quickly by PHP or other languages.  JSON is quite similar in structure to PHP arrays.  JSON data is created by nested key-value pairs where the value can be a number, string, Boolean, null, object or array. Two built-in functions are used in PHP to encode and decode JSON data. These are json_encode() and json_decode(). In this tutorial, you will learn how you can generate and parse JSON data in various ways using PHP.

Encoding JSON data using PHP

PHP uses json_encode() method to convert PHP array into JSON data.

Example-1:

In the following example, an array is declared and after encoding the data will be generated in json format.

<?php
//PHP Array
$animals = array("Lion", "Monkey", "Fox", "Deer", "Rat", "Dog", "Cat");
echo json_encode($animals);
?>

Output:

Example-2:

In the following example, a array is declared and the values of array are encoded using JSON_FORCE_OBJECT parameter to generate JSON data with key-value pairs.

<?php
// PHP  Array
$food = array("Cake", "Chocolate", "Ice Cream", "Pepsi", "Bread", "Fish curry", "Chicken Fry");
// array is converted as array or object
echo json_encode($food, JSON_FORCE_OBJECT);
?>

Output:

Example-3:

In the following example, an associative array is declared and after encoding it generates JSON data as key-value pairs without using any parameter.

<?php
//Associative array
$persons = array("John"=>35, "Peter"=>20, "Mark"=>68, "Lisa"=>30);
echo json_encode($persons);
?>

Output:

By following the above steps, you can easily convert any type of PHP array into JSON data format using json_encode() method. If you want to send or exchange small amount of data from one location another location then you can convert the data into JSON format and export it easily. After importing JSON data you will need to read the data in PHP format. To do this task you can follow the next part of this tutorial.

Decoding JSON data using PHP

You can parse or read JSON data from JSON object or any JSON file using PHP json_decode() method. Different examples of parsing JSON data using PHP are given below.

Example-1:

In the following example, JSON data is assigned in a variable and PHP json_decode() method is used to read the data in PHP format.

<?php
// Store JSON data in a PHP variable
$persons = '{"John":35,"Peter":40,"Mac":28,"Lisa":20}';
var_dump(json_decode($persons));
?>

Output:

The output shows the array keys and values with data type. Here, age value of any person is set numeric. So, data type, int is showing in the output.

Example-2:

In the following example, marks data with roll number are assigned in JSON format. If you use optional boolean parameter of json_encode() method then the output will show the object type with total number of elements. Here, the output shoes array object with 6 elements.

<?php
// Store JSON data in a PHP variable
$marks = '{"1001":95,"1002":80,"1003":78,"1004":90, "1005":83,"1006":92}';
var_dump(json_decode($marks,true));
?>

Output:

Example -3:

The following example shows how you can read each element of JSON data as array index and object property. In the script, $age variable which contains JSON data is decoded as array and object by using optional true parameter. Two types of output are generated here. The  elements are parsed by array index in the first part and parsed by objects property in the second part.

<?php
//Assign JSON encoded string to a PHP variable
$age = '{"Poll":55,"Devid":40,"Akbar":68,"Cally":70}';

// Decode JSON data to PHP associative array
$arr = json_decode($age, true);
echo "Parsing data by using PHP Array <br/>";

// Access values from the associative array
echo $arr["Poll"]."<br/>";
echo $arr["Devid"]."<br/>";
echo $arr["Akbar"]."<br/>";
echo $arr["Cally"]."<br/>";
$obj = json_decode($age);
echo "Parsing data by using PHP Object <br/>";

// Access values from the returned object
echo $obj->Poll."<br/>";
echo $obj->Devid."<br/>";
echo $obj->Akbar."<br/>";
echo $obj->Cally."<br/>";
?>

Output:

Example-4:

Using loop is the most efficient way to read array variable. The following example shows how you can parse JSON data using for loop after decoding. Here, the property names of JSON data are assigned as array index and property values are assigned as array values.

<?php
//Assign JSON encoded string to a PHP variable
$age = '{"Poll":55,"Devid":40,"Akbar":68,"Cally":70}';

// Decode JSON data to PHP associative array
$array = json_decode($age, true);

// Loop through the associative array
foreach($array as $key=>$value)
{
    echo $key . "=>" . $value . "<br>";
}
?>

Output:

Example-5:

In the above examples, JSON data are parsed from the particular variable but many times it is required to parse data from JSON file.

Suppose you have a JSON file named employees.json with the following content.

[
  {"Name":"Adam","Post": "Assistant Manager",
   "Address":{"Street":"1000 Brooklyn Meadow","City":"Denver"},
   "Email":"adam@gmail.com", "Phone": "+47349900047"},
  {"Name":"Bob","Post": "Manager",
   "Address":{"Street":"23 Sharp Crescent","City":"Bristol"},
   "Email":"bob@gmail.com", "Phone":"+479975047"},
  {"Name":"Kate","Post": "CEO",
   "Address":{"Street":"7 Yuki Street","City":"Tokyo"},
   "Email":"kate@gmail.com", "Phone": "+47377800047"}
]

You have to use file_get_contents() method to read JSON file before decoding the data. In the following script, data of  JSON file are printed as array  and in the last part of the script it is shown the way to read particular property value of JSON data. Here, the values of the “Name” property are printed using for loop.

<?php
// Read JSON file
$readjson = file_get_contents('employees.json') ;

//Decode JSON
$data = json_decode($readjson, true);

//Print data
print_r($data);
echo "<br/><br/> Employee names are: <br/>";

//Parse the employee name
foreach ($data as $emp) {
  echo $emp['Name']."<br/>";
}
?>

After reading and doing the above examples of this tutorial, you will able to create or parse any JSON data using PHP very easily.

About the author

Fahmida Yesmin

Fahmida Yesmin

I am a trainer of web programming courses. I like to write article or tutorial on various IT topics. I have a YouTube channel where many types of tutorials based on Ubuntu, Windows, Word, Excel, WordPress, Magento, Laravel etc. are published: Tutorials4u Help.