John Mwaniki / 04 Sep 2021
What is JSON?
JavaScript Object Notation[JSON] is a lightweight human-readable text format for storing and transporting data consisting of name-value pairs and arrays.
It is easy to generate and parse in many programming languages. It is the most popular and lightweight data-interchange format for web applications, and the de-facto format for the data exchange in RESTful web services requests and responses.
In this post, we will cover how to decode a JSON object and access its data in PHP.
Below is an example of a simple JSON object:
{
"firstName": "John",
"lastName": "Doe",
"email": "",
"phone": "111-111-1111"
}
How to receive JSON data in PHP
1. From a POST or GET request
To receive JSON data as a POST request, we use the “php://input” along with the function file_get_contents[] as below:
$json = file_get_contents["php://input"];
For instance, the JSON data is sent below as a POST request: