By Roshan Jha on Feb 10, 2021
JSON stands for JavaScript Object Notation. It was first specified and popularized by Douglas Crockford. JSON is widely used for real-time communication between the browser and the server. It also plays a crucial role in apps by storing frequently accessed data, enabling faster load times and offline availability of content—like messages in WhatsApp or the newsfeed in Facebook.
JSON is a lightweight and efficient format for transferring data between the browser and the server. It is supported by all major programming languages, including Python, Java, JavaScript, C#, and C++. One of the most commonly used backend languages that supports JSON is PHP.
JSON stores data as key/value pairs and is typically saved in .json
files. It supports data types such as:
Strings
Numbers
Booleans (true
/false
)
Null
Arrays
Objects
While JSON syntax is similar to JavaScript objects, it is actually transmitted as a string. This string is then parsed and converted into native data types by programming languages.
PHP interacts with JSON in two primary ways:
Converting JSON data into PHP objects or arrays
Converting PHP objects or arrays into JSON data
Let’s explore both methods with examples.
To convert JSON data into PHP, we use the built-in json_decode()
function.
Syntax:
Parameters:
$json
: (Required) The JSON string to decode.
$assoc
: (Optional) When true
, returns an associative array. When false
, returns an object. Default is false
.
$depth
: (Optional) Specifies recursion depth.
$flags
: (Optional) Bitmask of options like JSON_OBJECT_AS_ARRAY
, JSON_BIGINT_AS_STRING
, JSON_THROW_ON_ERROR
.
Since $assoc
is not specified, the default behavior converts the JSON string into a PHP object.
Here, by passing true
as the second parameter, the JSON string is converted into an associative array.
To convert PHP data (objects or arrays) into JSON, we use the json_encode()
function.
Syntax:
Parameters:
$value
: (Required) The value to be encoded.
$flags
: (Optional) Bitmask of options like JSON_PRETTY_PRINT
, JSON_UNESCAPED_UNICODE
, etc.
$depth
: (Optional) Maximum depth of recursion.
This is useful for preparing data to be sent to the client-side, saved in a file, or stored in a database.
json_encode()
vs json_decode()
Hopefully, this article helped you understand how to work with JSON in PHP. Whether you're sending data to a client-side application, saving it on a server, or interacting with external APIs, these functions—json_encode()
and json_decode()
—are essential tools for any PHP developer. Mastering JSON will also prepare you to use AJAX, REST APIs, and JavaScript more effectively in your PHP projects.