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

PHP JSON Handling

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
$data = ["name" => "Alice", "age" => 30];
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
$json = '{"name": "Alice", "age": 30}';
$obj = json_decode($json);
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
$json = '{"name": "Alice", "age": 30}';
$arr = json_decode($json, true);
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
$json = '{invalid json}';
$result = json_decode($json);
if (json_last_error() !== JSON_ERROR_NONE) {
    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
$data = ["name" => "Alice", "age" => 30];
echo json_encode($data, JSON_PRETTY_PRINT);
?>

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.