How to Parse JSON in PHP

28/12/2020
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":"[email protected]", "Phone": "+47349900047"},
  {"Name":"Bob","Post": "Manager",
   "Address":{"Street":"23 Sharp Crescent","City":"Bristol"},
   "Email":"[email protected]", "Phone":"+479975047"},
  {"Name":"Kate","Post": "CEO",
   "Address":{"Street":"7 Yuki Street","City":"Tokyo"},
   "Email":"[email protected]", "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.

ONET IDC thành lập vào năm 2012, là công ty chuyên nghiệp tại Việt Nam trong lĩnh vực cung cấp dịch vụ Hosting, VPS, máy chủ vật lý, dịch vụ Firewall Anti DDoS, SSL… Với 10 năm xây dựng và phát triển, ứng dụng nhiều công nghệ hiện đại, ONET IDC đã giúp hàng ngàn khách hàng tin tưởng lựa chọn, mang lại sự ổn định tuyệt đối cho website của khách hàng để thúc đẩy việc kinh doanh đạt được hiệu quả và thành công.
Bài viết liên quan

PHP String Concatenation

Joining one or more string value with other string value or variable is called string concatenation. It is a common task...
28/12/2020

Install CakePHP on Ubuntu

Many MVC based PHP frameworks are available now to make web developing tasks simpler and easier than before. In an MVC...
28/12/2020

How to Print Arrays in PHP

Array variables are used to store multiple values in a single variable.  Sometimes it is required to check the structure...
29/12/2020
Bài Viết

Bài Viết Mới Cập Nhật

Tìm Hiểu Về Thuê Proxy US – Lợi Ích và Cách Sử Dụng Hiệu Quả
11/12/2024

Mua Proxy V6 Nuôi Facebook Spam Hiệu Quả Tại Onetcomvn
03/06/2024

Hướng dẫn cách sử dụng ProxyDroid để duyệt web ẩn danh
03/06/2024

Mua proxy Onet uy tín tại Onet.com.vn
03/06/2024

Thuê mua IPv4 giá rẻ, tốc độ nhanh, uy tín #1
28/05/2024