PHP and JSON
🌐 PHP and JSON Tutorial
PHP can encode and decode JSON data, which is essential for API communication, AJAX requests, and data storage. JSON (JavaScript Object Notation) is a lightweight data-interchange format.
1️⃣ Encode PHP Array to JSON
Use json_encode() to convert PHP arrays or objects into a JSON string:
Output:
✅ json_encode() converts PHP associative arrays to JSON objects and indexed arrays to JSON arrays.
2️⃣ Decode JSON to PHP
Use json_decode() to convert a JSON string back to PHP variable:
Decode to associative array:
-
The second parameter
trueconverts JSON to associative array instead of object.
3️⃣ JSON with Indexed Arrays
4️⃣ JSON Pretty Print
Use JSON_PRETTY_PRINT for readable JSON format:
Output:
5️⃣ JSON Error Handling
Use json_last_error() to check for encoding/decoding errors:
Output:
6️⃣ Example: PHP & AJAX JSON Communication
PHP Script (data.php):
AJAX Request (JavaScript):
🏁 Summary
-
json_encode()→ PHP array/object to JSON -
json_decode()→ JSON string to PHP array/object -
Use
trueinjson_decode()for associative array -
JSON_PRETTY_PRINT→ Makes JSON readable -
json_last_error()→ Detect JSON errors -
JSON is commonly used for APIs, AJAX, and data exchange
