PHP JSON Handling
In this page:
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
$data = ["name" => "Alice", "age" => 30];
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
$json = '{"name": "Alice", "age": 30}';
$obj = json_decode($json);
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
$json = '{"name": "Alice", "age": 30}';
$arr = json_decode($json, true);
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
$json = '{invalid json}';
$result = json_decode($json);
if (json_last_error() !== JSON_ERROR_NONE) {
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
$data = ["name" => "Alice", "age" => 30];
echo json_encode($data, JSON_PRETTY_PRINT);
?>
Login to try C/C++/Java/PHP code in the editor
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