PHP and JSON

PHP Tutorial

 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:

{"name":"Vipul","email":"vipul@example.com","age":25}

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 true converts 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 JSON

  • json_decode() → JSON string to array/object

  • Use true in json_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

You may also like...