Cheat Sheets & Quick References

PHP JSON Handling Cheat Sheet

A quick reference to encoding, decoding and handling JSON data safely with PHP.

Overview

JSON is commonly used for API requests, configuration and data exchange. PHP's JSON extension provides functions for converting between PHP values and JSON text.

Common functions

  • json_encode() converts PHP values to JSON.
  • json_decode() parses JSON into objects or associative arrays.
  • json_last_error() and json_last_error_msg() inspect errors when exceptions are not used.
  • The JSON_THROW_ON_ERROR flag makes encoding and decoding failures explicit through exceptions.

Practical guidance

Validate the expected data shape after decoding. Do not assume syntactically valid JSON is semantically valid input. Set appropriate response headers for JSON APIs and avoid returning internal exception details to clients.

Official resource

PHP JSON Functions