JSON with PHP
15 April 2025 | Category: JavaScript
JSON (JavaScript Object Notation) is a lightweight data format used for data exchange between server and client. In PHP, you can encode PHP data to JSON and decode JSON data to PHP.
â JSON is commonly used when sending/receiving data in APIs, especially in AJAX or RESTful apps.
đ PHP and JSON Conversion Functions
Function | Purpose |
---|---|
json_encode() | Converts PHP data to JSON string |
json_decode() | Converts JSON string to PHP data |
đš 1. Encoding PHP Data to JSON
⤠Example 1: Encode an Associative Array
<?php
$data = array("name" => "Alice", "age" => 25, "city" => "Delhi");
$jsonData = json_encode($data);
echo $jsonData;
?>
â Output:
{"name":"Alice","age":25,"city":"Delhi"}
⤠Example 2: Encode a Multidimensional Array
<?php
$users = array(
array("id" => 1, "name" => "Alice"),
array("id" => 2, "name" => "Bob")
);
echo json_encode($users);
?>
â Output:
[
{"id":1,"name":"Alice"},
{"id":2,"name":"Bob"}
]
đš 2. Decoding JSON to PHP
⤠Example: Decode JSON to Associative Array
<?php
$json = '{"name":"Alice","age":25,"city":"Delhi"}';
$phpArray = json_decode($json, true); // true returns associative array
print_r($phpArray);
?>
â Output:
Array
(
[name] => Alice
[age] => 25
[city] => Delhi
)
⤠Decode JSON to PHP Object
<?php
$json = '{"name":"Alice","age":25}';
$phpObject = json_decode($json); // default returns object
echo $phpObject->name;
?>
â Output:
Alice
đ Handling JSON Errors
You can check for errors using:
<?php
$data = "\xB1\x31"; // Invalid UTF-8
json_encode($data);
if (json_last_error() !== JSON_ERROR_NONE) {
echo "JSON Encode Error: " . json_last_error_msg();
}
?>
đ JSON with PHP in AJAX Requests
⤠Example: Returning JSON from PHP (for frontend use)
<?php
header('Content-Type: application/json');
$data = array("status" => "success", "message" => "Data fetched!");
echo json_encode($data);
?>
This PHP file can be called using AJAX from JavaScript and used like an API.
â Summary
Task | Function Used |
---|---|
Encode PHP to JSON | json_encode() |
Decode JSON to PHP | json_decode() |
Error Handling | json_last_error() |
AJAX Responses | Use header() + json_encode() |
đŚ Real Use Case
A sample AJAX + PHP + JSON setup:
// JavaScript (frontend)
fetch("data.php")
.then(res => res.json())
.then(data => {
console.log(data.message);
});
// data.php
<?php
header("Content-Type: application/json");
echo json_encode(["message" => "Hello from PHP!"]);
?>