JSON (JavaScript Object Notation) is a lightweight format used to exchange data between the client and server. PHP provides built-in functions like json_encode()
to convert PHP arrays/objects to JSON and json_decode()
to parse JSON into PHP. This is essential for APIs, AJAX, and file handling. You can also read/write JSON files using file_get_contents()
and file_put_contents()
. PHP and JSON together enable efficient, structured data exchange in web applications.
1. What is JSON?
- JSON is a text format for storing and transporting data.
- Example JSON:
{
"name": "John",
"age": 25
}
2. json_encode()
– Convert PHP to JSON
$data = [
"name" => "John",
"age" => 25,
"skills" => ["PHP", "Laravel", "MySQL"]
];
$json = json_encode($data);
echo $json;
File: json_encode_demo.php
Output:
{"name":"John","age":25,"skills":["PHP","Laravel","MySQL"]}
3. json_decode()
– Convert JSON to PHP
$jsonString = '{"name":"John","age":25}';
$data = json_decode($jsonString, true); // true = associative array
echo $data["name"]; // Output: John
File: json_decode_demo.php
4. Working with Objects from JSON
$jsonString = '{"name":"John","age":25}';
$data = json_decode($jsonString); // default = object
echo $data->name; // Output: John
5. Send JSON from PHP to JavaScript (AJAX)
header('Content-Type: application/json');
$response = [
"status" => "success",
"message" => "Data received"
];
echo json_encode($response);
File: api_response.php
6. Save JSON to a File
$data = ["user" => "John", "role" => "admin"];
$jsonData = json_encode($data, JSON_PRETTY_PRINT);
file_put_contents("data.json", $jsonData);
File: json_write.php
7. Read JSON File
$jsonContent = file_get_contents("data.json");
$data = json_decode($jsonContent, true);
print_r($data);
File: json_read.php
Summary Table
Task | PHP Function | File to Use |
---|---|---|
Encode PHP → JSON | json_encode() |
json_encode_demo.php |
Decode JSON → PHP array | json_decode(..., true) |
json_decode_demo.php |
Decode JSON → object | json_decode() |
json_decode_demo.php |
Return JSON response | echo json_encode() |
api_response.php |
Write JSON to file | file_put_contents() |
json_write.php |
Read JSON from file | file_get_contents() |
json_read.php |