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 7.1.3 released with lots of bug fixes – Install PHP 7 on Linux

PHP 7.1.3 recently released, is a popular general-purpose scripting language that is especially suited to web development....
28/12/2020

Setting up a Debian 10 LAMP Server for PHP Web Development

In this article, I am going to show you how to setup a LAMP (Linux, Apache, MySQL/MariaDB, PHP) server for PHP web development....
29/12/2020

Building a Contact Form in PHP

How to create contact form using HTML, CSS and PHP A contact form is a very essential part of any website. The visitors...
28/12/2020
Bài Viết

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

Mua proxy v4 chạy socks5 để chơi game an toàn, tốc độ cao ở đâu?
18/05/2024

Thuê mua proxy Telegram trọn gói, tốc độ cao, giá siêu hời
18/05/2024

Thuê mua proxy Viettel ở đâu uy tín, chất lượng và giá tốt? 
14/05/2024

Dịch vụ thuê mua proxy US UK uy tín, chất lượng số #1
13/05/2024

Thuê mua proxy Việt Nam: Báo giá & các thông tin MỚI NHẤT
13/05/2024