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.
Encode Array to JSON
Use json_encode() to convert PHP arrays or objects into a JSON string:
Output:
json_encode() converts associative arrays to JSON objects and indexed arrays to JSON arrays.
Decode JSON to Personal Home Page
Use json_decode() to convert a JSON string back to Personal Home Page variable:
Decode to associative array:
The second parameter
trueconverts JSON to associative array instead of object.
JSON with Indexed Arrays
JSON Pretty Print
Use JSON_PRETTY_PRINT for readable JSON format:
Output:
JSON Error Handling
Use json_last_error() to check for encoding/decoding errors:
Output:
Example: Personal Home Page & AJAX JSON Communication
PHP Script (data.php):
AJAX Request (JavaScript):
Summary
json_encode()→ array/object to JSONjson_decode()→ JSON string to array/objectUse
trueinjson_decode()for associative arrayJSON_PRETTY_PRINT→ Makes JSON readablejson_last_error()→ Detect JSON errorsJSON is commonly used for APIs, AJAX, and data exchange
