-
Hajipur, Bihar, 844101
Hajipur, Bihar, 844101
JS Basics
JS Variables & Operators
JS Data Types & Conversion
JS Numbers & Math
JS Strings
JS Dates
JS Arrays
JS Control Flow
JS Loops & Iteration
JS Functions
JS Functions
Function Definitions
Function Parameters
Function Invocation
Function Call
Function Apply
Function Bind
Function Closures
JS Arrow Function
JS Objects
JS Objects
JS Object Properties
JS Object Methods
JS Object Display
JS Object Constructors
Object Definitions
Object Get / Set
Object Prototypes
Object Protection
JS Classes & Modules
JS Async Programming
JS Advanced
JS Destructuring
JS Bitwise
JS RegExp
JS Precedence
JS Errors
JS Scope
JS Hoisting
JS Strict Mode
JS this Keyword
JS HTML DOM
DOM Intro
DOM Methods
DOM Document
DOM Elements
DOM HTML
DOM Forms
DOM CSS
DOM Animations
DOM Events
DOM Event Listener
DOM Navigation
DOM Nodes
DOM Collections
DOM Node Lists
JS BOM (Browser Object Model)
JS Web APIs
Web API Intro
Web Validation API
Web History API
Web Storage API
Web Worker API
Web Fetch API
Web Geolocation API
JS AJAX
AJAX Intro
AJAX XMLHttp
AJAX Request
AJAX Response
AJAX XML File
AJAX PHP
AJAX ASP
AJAX Database
AJAX Applications
AJAX Examples
JS JSON
JSON Intro
JSON Syntax
JSON vs XML
JSON Data Types
JSON Parse
JSON Stringify
JSON Objects
JSON Arrays
JSON Server
JSON PHP
JSON HTML
JSON JSONP
JS Graphics & Charts
JSON is widely used to exchange data between a client (like a web browser) and a server. In PHP, JSON is fully supported, making it easy to encode PHP data into JSON for sending to a client or decode JSON received from a client.
PHP is a server-side language, and when building APIs or dynamic web applications, you often need to send data in JSON format. JSON is lightweight, human-readable, and compatible with JavaScript, making it ideal for web communication.
Encode PHP arrays or objects into JSON.
Decode JSON strings into PHP arrays or objects.
Communicate with front-end applications using AJAX or fetch APIs.
To convert PHP data into JSON, you use the built-in function json_encode()
.
<?php
$user = array(
"name" => "Vicky",
"age" => 28,
"isDeveloper" => true
);
$jsonData = json_encode($user);
echo $jsonData;
?>
Output:
{"name":"Vicky","age":28,"isDeveloper":true}
Explanation:
json_encode()
converts a PHP associative array into a JSON string.
This JSON can now be sent to a browser or stored in a file.
<?php
class User {
public $name;
public $age;
public $isDeveloper;
function __construct($name, $age, $isDeveloper) {
$this->name = $name;
$this->age = $age;
$this->isDeveloper = $isDeveloper;
}
}
$user = new User("Sanjana", 26, false);
echo json_encode($user);
?>
Output:
{"name":"Sanjana","age":26,"isDeveloper":false}
PHP objects are automatically converted into JSON objects.
To convert JSON received from a client into PHP data, use json_decode()
.
<?php
$jsonString = '{"name":"Vicky","age":28,"isDeveloper":true}';
$user = json_decode($jsonString, true); // true converts it into an associative array
echo $user["name"]; // Output: Vicky
<?php
$jsonString = '{"name":"Sanjana","age":26,"isDeveloper":false}';
$user = json_decode($jsonString); // default is object
echo $user->name; // Output: Sanjana
The second parameter of json_decode()
determines whether the result is an associative array (true
) or an object (false
or default).
You can encode and decode arrays of data as well.
<?php
$users = array(
array("name" => "Vicky", "age" => 28),
array("name" => "Sanjana", "age" => 26)
);
echo json_encode($users);
?>
Output:
[
{"name":"Vicky","age":28},
{"name":"Sanjana","age":26}
]
Decoding this JSON back into PHP:
<?php
$jsonString = '[{"name":"Vicky","age":28},{"name":"Sanjana","age":26}]';
$users = json_decode($jsonString, true);
foreach ($users as $user) {
echo $user["name"] . "\n";
}
Output:
Vicky
Sanjana
When sending JSON data via PHP to a browser or front-end application, set the correct header:
<?php
header('Content-Type: application/json');
$data = array("message" => "Hello from PHP", "status" => true);
echo json_encode($data);
?>
header('Content-Type: application/json')
tells the browser that the response is in JSON format.
This is important when using AJAX or fetch to receive data.
Front-end applications often send JSON via POST requests. You can read and decode it in PHP:
<?php
// Read raw POST data
$jsonData = file_get_contents("php://input");
// Convert JSON to PHP array
$data = json_decode($jsonData, true);
echo "Hello, " . $data["name"];
?>
If a front-end sends this JSON:
{"name":"Vicky","age":28}
The output will be:
Hello, Vicky
Suppose you want to create a simple API endpoint that returns users:
<?php
header('Content-Type: application/json');
$users = array(
array("id" => 1, "name" => "Vicky", "age" => 28),
array("id" => 2, "name" => "Sanjana", "age" => 26)
);
echo json_encode($users);
?>
From the front-end, you can fetch the data:
fetch("users.php")
.then(response => response.json())
.then(data => console.log(data));
Output in console:
[
{"id":1,"name":"Vicky","age":28},
{"id":2,"name":"Sanjana","age":26}
]
Always set the header to application/json
for API responses.
Validate JSON when decoding to avoid errors:
$data = json_decode($jsonString, true);
if (json_last_error() !== JSON_ERROR_NONE) {
echo "Invalid JSON";
}
Use associative arrays if you prefer working with array syntax ($data['name']
) instead of object syntax ($data->name
).
Encode PHP objects carefully; private properties are not included by default.
json_encode()
converts PHP arrays or objects into JSON strings.
json_decode()
converts JSON strings into PHP arrays or objects.
Set Content-Type: application/json
when sending JSON to clients.
JSON arrays and objects are fully supported.
PHP and JSON work together seamlessly for API development, front-end integration, and AJAX communication.
Always validate and handle errors when decoding JSON from clients.
JSON in PHP makes it easy to build APIs, exchange data, and integrate front-end applications without complications.
Create a PHP associative array with keys name
, age
, and isDeveloper
. Convert it to JSON using json_encode()
and print it.
Create a PHP object for a user with name
, age
, and city
. Convert the object to JSON and print it.
Decode this JSON string into a PHP associative array and print the name
:
'{"name":"Sanjana","age":26,"isDeveloper":false}'
Decode the same JSON string into a PHP object and print the age
using object syntax.
Create a PHP array of two users (each user is an associative array with name
and age
) and encode it into a JSON array.
Write a PHP script that reads JSON from a POST request using file_get_contents("php://input")
and prints a greeting using the name
key.
Set the header to application/json
and send a JSON response with a status
and message
key.
Decode a JSON array of users and loop through it to print each user’s name. Example JSON:
'[{"name":"Vicky","age":28},{"name":"Sanjana","age":26}]'
Create a PHP script that validates a JSON string using json_last_error()
and prints "Valid JSON" or "Invalid JSON".
Encode a nested PHP array containing a user and their address (city
and zipcode
) into JSON and print the result.
JS Basics
JS Variables & Operators
JS Data Types & Conversion
JS Numbers & Math
JS Strings
JS Dates
JS Arrays
JS Control Flow
JS Loops & Iteration
JS Functions
JS Functions
Function Definitions
Function Parameters
Function Invocation
Function Call
Function Apply
Function Bind
Function Closures
JS Arrow Function
JS Objects
JS Objects
JS Object Properties
JS Object Methods
JS Object Display
JS Object Constructors
Object Definitions
Object Get / Set
Object Prototypes
Object Protection
JS Classes & Modules
JS Async Programming
JS Advanced
JS Destructuring
JS Bitwise
JS RegExp
JS Precedence
JS Errors
JS Scope
JS Hoisting
JS Strict Mode
JS this Keyword
JS HTML DOM
DOM Intro
DOM Methods
DOM Document
DOM Elements
DOM HTML
DOM Forms
DOM CSS
DOM Animations
DOM Events
DOM Event Listener
DOM Navigation
DOM Nodes
DOM Collections
DOM Node Lists
JS BOM (Browser Object Model)
JS Web APIs
Web API Intro
Web Validation API
Web History API
Web Storage API
Web Worker API
Web Fetch API
Web Geolocation API
JS AJAX
AJAX Intro
AJAX XMLHttp
AJAX Request
AJAX Response
AJAX XML File
AJAX PHP
AJAX ASP
AJAX Database
AJAX Applications
AJAX Examples
JS JSON
JSON Intro
JSON Syntax
JSON vs XML
JSON Data Types
JSON Parse
JSON Stringify
JSON Objects
JSON Arrays
JSON Server
JSON PHP
JSON HTML
JSON JSONP
JS Graphics & Charts