JSON is a text format for representing and exchanging structured data between applications.
JSON (JavaScript Object Notation) is a lightweight text format for data exchange. Although it comes from JavaScript, PHP handles it natively and extremely efficiently. It is essential for creating APIs and communicating your backend (PHP) with the frontend (React, Vue, pure JS).
json_encode: from PHP to text (JSON)
This function takes a PHP array or object and converts it into a JSON formatted string. It’s what you do when you want to “send” data to the outside world.
Syntax:
string json_encode ( mixed $value [, int $flags ] )
Example:
$user = [
"name" => "Carlos",
"age" => 30,
"active" => true,
"skills" => ["PHP", "SQL", "Git"]
];
// Convert the PHP array to JSON
// JSON_UNESCAPED_UNICODE ensures accents and ñ display correctly
// JSON_PRETTY_PRINT makes the JSON human-readable (with line breaks)
$jsonText = json_encode($user, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
echo $jsonText;Generated output (String):
{
"name": "Carlos",
"age": 30,
"active": true,
"skills": [
"PHP",
"SQL",
"Git"
]
}json_decode: from text (JSON) to PHP
This function does the opposite: it takes a JSON string (perhaps received from an external API or read from a file) and converts it into a PHP data structure.
The “Trick” with the second parameter: This is the number one source of confusion in PHP.
- If you use
json_decode($json), PHP creates an Object (stdClass). - If you use
json_decode($json, true), PHP creates an Associative Array.
| Mode | Code | Accessing data |
|---|---|---|
| Object (Default) | $data = json_decode($json); | $data->name |
| Array (Recommended) | $data = json_decode($json, true); | $data['name'] |
Example:
$receivedJson = '{"product": "Monitor", "price": 200}';
// Object mode
$obj = json_decode($receivedJson);
echo $obj->product; // Output: Monitor
// Array mode (More common if you work with arrays in the rest of your code)
$arr = json_decode($receivedJson, true);
echo $arr['product']; // Output: MonitorJSON error handling
Sometimes the JSON you receive is malformed (missing a comma, a quote, etc.). If json_decode fails, it returns null, which can be dangerous if you don’t check it.
Since PHP 7.3+, the best way to handle this is to combine it with what we learned at the beginning of the module: Exceptions. We use the JSON_THROW_ON_ERROR flag.
$corruptJson = '{"name": "John" ... syntax error ... }';
try {
// This will automatically throw an exception if the JSON is malformed
$data = json_decode($corruptJson, true, 512, JSON_THROW_ON_ERROR);
} catch (JsonException $e) {
echo "Error processing JSON!: " . $e->getMessage();
}