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:

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

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

CodeCapsule

Sanjit Sinha — Web Developer | PHP • Laravel • CodeIgniter • MySQL • Bootstrap Founder, CodeCapsule — Student projects & practical coding guides. Email: info@codecapsule.in • Website: CodeCapsule.in

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *