π¦ PHP JSON Handling – Encode & Decode JSON Data
JSON (JavaScript Object Notation) is a **lightweight data format** used for **data exchange** between systems. Itβs widely used in APIs, web applications, and more.
In PHP, we use json_encode()
to convert data into JSON format and json_decode()
to convert JSON back into PHP data structures.
π Encoding PHP Data to JSON
The json_encode()
function converts PHP arrays or objects into a JSON string.
β Example: Convert PHP Array to JSON
Letβs encode an array of fruits into JSON format.
<?php $fruits = array("Apple", "Banana", "Cherry"); $jsonData = json_encode($fruits); echo $jsonData; ?>
π Output:
["Apple","Banana","Cherry"]
(JSON format!)
π Decoding JSON to PHP
The json_decode()
function converts a JSON string back into a PHP array or object.
β Example: Convert JSON to PHP Array
Letβs decode JSON data into a PHP array.
<?php $jsonData = '["Apple","Banana","Cherry"]'; $phpArray = json_decode($jsonData, true); print_r($phpArray); ?>
π Output:
Array ( [0] => Apple [1] => Banana [2] => Cherry )
Passing true
as the second parameter makes it return an **associative array** instead of an object.
π Encoding & Decoding PHP Objects
JSON also works with PHP objects. Letβs convert a PHP object to JSON and back.
β Example: Convert PHP Object to JSON
<?php class Fruit { public $name; public $color; } $apple = new Fruit(); $apple->name = "Apple"; $apple->color = "Red"; $jsonData = json_encode($apple); echo $jsonData; ?>
π Output:
{"name":"Apple","color":"Red"}
β Example: Convert JSON to PHP Object
<?php $jsonData = '{"name":"Apple","color":"Red"}'; $phpObject = json_decode($jsonData); echo "Fruit: " . $phpObject->name . ", Color: " . $phpObject->color; ?>
π Output:
Fruit: Apple, Color: Red
π§ Handling JSON Errors
If JSON encoding or decoding fails, you can check for errors using json_last_error()
.
β Example: Detect JSON Errors
<?php $invalidJson = "{name: 'Apple', color: 'Red'}"; // Missing quotes around keys $jsonData = json_decode($invalidJson); if (json_last_error() !== JSON_ERROR_NONE) { echo "β JSON Error: " . json_last_error_msg(); } ?>
π Output:
β JSON Error: Syntax error
π― Best Practices for JSON Handling
- β
Always validate JSON with
json_last_error()
. - β
Use
json_encode()
for PHP β JSON conversion. - β
Use
json_decode()
withtrue
for arrays. - β Ensure JSON strings use **double quotes** around keys.
- β Secure JSON data before processing it in APIs.
π Next Steps
Now that you understand PHP JSON handling, try using it in **APIs, file storage, or AJAX calls**! Happy coding! π