PHP JSON Handling
In this page:
$json = json_encode($data); // PHP value to JSON string
$object = json_decode($json); // to stdClass object
$array = json_decode($json, true); // to associative array
Encoding Data to JSON
json_encode() turns PHP arrays or objects into a JSON string, which is the standard format for sending structured data to a JavaScript frontend or a third-party API.
Example: Encoding Data to JSON
<?php
// Declare `$data` as an array: `["name" => "Alice", "age" => 30]`
$data = ["name" => "Alice", "age" => 30];
// Print `json_encode($data)` to the output
echo json_encode($data);
?>
Login to try C/C++/Java/PHP code in the editor
Decoding JSON to Objects
json_decode() parses a JSON string back into PHP values; by default it produces nested stdClass objects, so you access fields with -> rather than array bracket syntax.
Example: Decoding JSON to Objects
<?php
// Declare `$json`, set to '{"name": "Alice", "age": 30}'
$json = '{"name": "Alice", "age": 30}';
// Declare `$obj`, set to `json_decode($json)`
$obj = json_decode($json);
// Print `$obj->name` to the output
echo $obj->name;
?>
Login to try C/C++/Java/PHP code in the editor
Decoding JSON to Associative Arrays
Passing true as json_decode()'s second argument decodes the same JSON into nested associative arrays instead of objects, which many developers find more convenient to work with in PHP.
Example: Decoding JSON to Associative Arrays
<?php
// Declare `$json`, set to '{"name": "Alice", "age": 30}'
$json = '{"name": "Alice", "age": 30}';
// Declare `$arr`, set to `json_decode($json, true)`
$arr = json_decode($json, true);
// Print `$arr['name']` to the output
echo $arr['name'];
?>
Login to try C/C++/Java/PHP code in the editor
Handling JSON Errors
Malformed JSON causes json_decode() to silently return null, so checking json_last_error() (or reading json_last_error_msg() for a human-readable reason) is essential before trusting the decoded result.
Example: Handling JSON Errors
<?php
// Declare `$json`, set to '{invalid json}'
$json = '{invalid json}';
// Declare `$result`, set to `json_decode($json)`
$result = json_decode($json);
// Check whether `json_last_error() !== JSON_ERROR_NONE`
if (json_last_error() !== JSON_ERROR_NONE) {
// Print `"Error: " . json_last_error_msg()` to the output
echo "Error: " . json_last_error_msg();
}
?>
Login to try C/C++/Java/PHP code in the editor
JSON Encoding Options
Passing the JSON_PRETTY_PRINT flag to json_encode() adds indentation and line breaks to the output, which is useful for debugging API responses but should generally be skipped in production for smaller payloads.
Example: JSON Encoding Options
<?php
// Declare `$data` as an array: `["name" => "Alice", "age" => 30]`
$data = ["name" => "Alice", "age" => 30];
// Print `json_encode($data, JSON_PRETTY_PRINT)` to the output
echo json_encode($data, JSON_PRETTY_PRINT);
?>
Login to try C/C++/Java/PHP code in the editor
- Not checking
json_last_error()afterjson_decode, so invalid JSON silently returns null. - Forgetting the second argument
trueto get an associative array, and then using array syntax on an object. - Encoding text that is not valid UTF-8, which makes
json_encodereturn false.
Chapter Quiz — Complete all 24 topics to unlock
0/24 topics done
Complete these topics first:
- PHP Date & Time
- PHP Math Functions
- PHP JSON Handling
- PHP XML Handling
- PHP cURL Introduction
- PHP REST API Basics
- PHP Composer & Packages
- PHP Autoloading
- PHP Design Patterns
- PHP MVC Architecture
- PHP Security Best Practices
- PHP Performance Optimization
- PHP 8 New Features
- PHP Type Declarations
- PHP Match Expression Advanced
- PHP Fibers
- PHP Attributes
- PHP Magic Constants
- PHP Include & Require
- PHP Iterables
- PHP SimpleXML Parser
- PHP SimpleXML Get
- PHP XML Expat Parser
- PHP DOM Parser