🧪 PHP Advanced Topics
Estimated reading: 3 minutes 279 views

PHP JSON – Encode and Decode JSON Data in PHP

Learn how to work with JSON in PHP to handle structured data for APIs, configuration files, AJAX responses, and more.


Introduction – Why JSON Is Important in PHP

JSON (JavaScript Object Notation) is the most popular data-interchange format on the web. It’s lightweight, human-readable, and natively supported by JavaScript — making it perfect for AJAX communication, REST APIs, and client-server data exchange.

PHP provides built-in functions to seamlessly encode and decode JSON, making it easy to work with structured data formats.

In this guide, you’ll learn:

  • How to convert PHP arrays/objects to JSON
  • How to parse JSON into PHP variables
  • How to handle JSON errors
  • Common use cases and best practices

PHP JSON Functions

FunctionDescription
json_encode()Convert PHP array/object to JSON string
json_decode()Convert JSON string to PHP variable
json_last_error()Check for encoding/decoding errors

Encoding PHP to JSON

$data = [
  "name" => "Alice",
  "email" => "alice@example.com"
];

$json = json_encode($data);
echo $json;

Output:

{"name":"Alice","email":"alice@example.com"}

Use json_encode() to send structured data to the browser or API clients


Decoding JSON to PHP

$json = '{"name":"Bob","age":30}';
$data = json_decode($json, true);

echo $data['name']; // Output: Bob

Set the second parameter to true to convert to associative array
If false or omitted, the result is an object


Handling JSON Errors

$json = '{"name":"Bob", "age":}'; // malformed JSON

$data = json_decode($json);
if (json_last_error() !== JSON_ERROR_NONE) {
    echo " JSON error: " . json_last_error_msg();
}

Always validate the JSON string before processing it


Security & Best Practices

  • Use json_encode() before storing complex data in cookies or local storage
  • Escape JSON in HTML with care to avoid XSS
  • Avoid circular references in objects passed to json_encode()
  • Validate user-provided JSON using schema libraries if needed

Common JSON Flags

json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
FlagPurpose
JSON_PRETTY_PRINTFormats output for readability
JSON_UNESCAPED_UNICODEKeeps non-ASCII chars (e.g., emojis)
JSON_UNESCAPED_SLASHESLeaves slashes (e.g., URLs) unescaped

Summary – Recap & Next Steps

JSON is central to modern web development, and PHP offers powerful tools to handle it easily. Whether you’re building APIs or working with AJAX, understanding JSON processing is essential.

Key Takeaways:

  • Use json_encode() to convert PHP arrays to JSON strings
  • Use json_decode() to parse JSON into arrays or objects
  • Always handle and validate JSON errors
  • Use flags for readable and Unicode-friendly JSON output

Real-World Use Cases:
AJAX responses, REST APIs, dynamic form data, API requests, config files


Frequently Asked Questions (FAQs)

How do I convert a PHP object to JSON?
Use json_encode($object)

How can I format JSON output for readability?
Use JSON_PRETTY_PRINT with json_encode()

What’s the difference between associative and object decoding?
Pass true as the second parameter to json_decode() to get an array instead of an object

Is it safe to accept JSON input from users?
Yes, but always validate and sanitize the decoded data before using it

Can I encode Unicode and emojis in JSON?
Yes, use JSON_UNESCAPED_UNICODE flag


Share Now :
Share

📦 PHP JSON

Or Copy Link

CONTENTS
Scroll to Top