JSON is one of the most important data formats used in REST APIs. In the previous lesson, we sent student data using a POST request. Now we will learn how PHP receives JSON data, converts JSON into PHP data, works with the values, and sends JSON back to the client.
JSON stands for JavaScript Object Notation. It is a lightweight text-based format used to exchange data between applications.
{
"name": "Rahul",
"course": "PHP"
}
JSON is easy for both humans and programming languages to read.
REST APIs need a common format for sending data between clients and servers. JSON is widely used for this purpose.
React Native
↕
JSON
↕
PHP REST API
The mobile application can send JSON to PHP and PHP can return JSON to the mobile application.
A JSON object contains data in key-value pairs.
{
"name": "Rahul",
"email": "rahul@example.com",
"course": "PHP"
}
The keys are written inside double quotes.
A JSON array can contain multiple values or objects.
[
{
"id": 1,
"name": "Rahul"
},
{
"id": 2,
"name": "Amit"
}
]
Arrays are useful when an API returns multiple records.
PHP provides built-in functions for working with JSON.
PHP Array
↓
json_encode()
↓
JSON
JSON
↓
json_decode()
↓
PHP Array
The json_encode() function converts PHP data into a JSON string.
$student = [
"name" => "Rahul",
"course" => "PHP"
];
echo json_encode($student);
The output is:
{"name":"Rahul","course":"PHP"}
When a PHP API returns JSON, set the response content type.
header("Content-Type: application/json");
This tells the client that the response contains JSON data.
<?php
header("Content-Type: application/json");
$response = [
"success" => true,
"message" => "API is working"
];
echo json_encode($response);
?>
The API returns a JSON object containing a success value and message.
The json_decode() function converts JSON into PHP data.
$json = '{
"name": "Rahul",
"course": "PHP"
}';
$data = json_decode($json, true);
The second parameter true makes the result an associative array.
After decoding JSON into an associative array, values can be accessed using their keys.
echo $data['name'];
echo $data['course'];
The output will be:
Rahul
PHP
A REST API can receive JSON through the HTTP request body.
$input = file_get_contents(
"php://input"
);
This reads the raw body sent by the client.
The raw JSON body can be converted into a PHP associative array.
$data = json_decode(
file_get_contents("php://input"),
true
);
Now the PHP code can work with the received values.
A React Native application or Postman can send:
{
"name": "Rahul",
"email": "rahul@example.com",
"mobile": "9876543210",
"course": "PHP"
}
PHP receives this JSON through the request body.
$data = json_decode(
file_get_contents("php://input"),
true
);
$name = $data['name'];
$email = $data['email'];
$mobile = $data['mobile'];
$course = $data['course'];
Each JSON property can now be accessed using PHP array syntax.
The null coalescing operator can be used when a JSON key may not exist.
$name = $data['name'] ?? '';
$email = $data['email'] ?? '';
$mobile = $data['mobile'] ?? '';
$course = $data['course'] ?? '';
If a key does not exist, an empty string is used.
The API should validate the received data before processing it.
if ($name === '' || $email === '') {
http_response_code(400);
echo json_encode([
"success" => false,
"message" => "Name and email are required"
]);
exit;
}
When sending JSON to an API, the client should identify the content type.
Content-Type: application/json
This tells the server that the request body contains JSON data.
PHP can return a student array as JSON.
$student = [
"id" => 1,
"name" => "Rahul",
"email" => "rahul@example.com",
"course" => "PHP"
];
echo json_encode($student);
Multiple PHP records can be converted into a JSON array.
$students = [
[
"id" => 1,
"name" => "Rahul"
],
[
"id" => 2,
"name" => "Amit"
]
];
echo json_encode($students);
A REST API can wrap the data inside a response object.
$response = [
"success" => true,
"message" => "Students fetched successfully",
"data" => $students
];
echo json_encode($response);
This makes the response easier for clients to understand.
Errors can also be returned as JSON.
http_response_code(400);
echo json_encode([
"success" => false,
"message" => "Invalid request"
]);
The client can check the HTTP status and JSON message.
Database records can be fetched using PDO and then converted to JSON.
$stmt = $pdo->query(
"SELECT id, name, email, mobile, course
FROM students"
);
$students = $stmt->fetchAll(
PDO::FETCH_ASSOC
);
echo json_encode([
"success" => true,
"data" => $students
]);
React Native
↓
JSON Request
↓
php://input
↓
json_decode()
↓
PHP Array
↓
MySQL
↓
PHP Array
↓
json_encode()
↓
JSON Response
↓
React Native
Postman can be used to test JSON requests.
Choose:
Method: POST
Body:
raw
JSON
Then enter:
{
"name": "Rahul",
"email": "rahul@example.com",
"mobile": "9876543210",
"course": "PHP"
}
If the client sends invalid JSON, json_decode() may not produce the expected PHP data.
For example, this is invalid JSON:
{
"name": "Rahul",
"email": "rahul@example.com",
}
There is an extra comma after the email value.
PHP provides json_last_error() to check the last JSON decoding or encoding error.
$data = json_decode(
$input,
true
);
if (json_last_error() !== JSON_ERROR_NONE) {
echo json_encode([
"success" => false,
"message" => "Invalid JSON"
]);
exit;
}
React Native can send JSON using JSON.stringify().
fetch("http://localhost/rest_api/api/students.php", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
name: "Rahul",
email: "rahul@example.com",
mobile: "9876543210",
course: "PHP"
})
});
The PHP API can receive this data using php://input.
React Native can convert a JSON HTTP response into JavaScript data using response.json().
fetch("http://localhost/rest_api/api/students.php")
.then(response => response.json())
.then(data => {
console.log(data);
});
This allows the application to work with the API response.
JSON is the main data exchange format we are using between our PHP REST API and React Native application. PHP uses json_decode() to read JSON received from the client and json_encode() to send PHP data back as JSON.
Client
↓
JSON
↓
json_decode()
↓
PHP
↓
MySQL
↓
PHP
↓
json_encode()
↓
JSON
↓
Client
Question: Which PHP function converts JSON data into PHP data?