← Back to PHP Course | Chapter 14: Advanced PHP | Lesson 3 of 24

PHP JSON Handling

JSON is a neat text format that computers use to swap information, like writing a shopping list everyone can read. PHP can turn its data into that text and turn the text back into data.
Syntax
php
$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
<?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);
?>

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
<?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;
?>

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
<?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'];
?>

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
<?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();
}
?>

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
<?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);
?>
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Not checking json_last_error() after json_decode, so invalid JSON silently returns null.
  2. Forgetting the second argument true to get an associative array, and then using array syntax on an object.
  3. Encoding text that is not valid UTF-8, which makes json_encode return false.

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.