JSON in PHP (json_encode, json_decode)
In this lesson: Convert PHP arrays to JSON and back with json_encode and json_decode — pretty print, errors and API examples.
What is JSON
JSON (JavaScript Object Notation) is a lightweight text format for storing and sending data. It looks like a PHP array written with {} and []. JSON is the standard way to pass data between a server and a browser, or in an API, because almost every language can read it.
json_encode (array → JSON) and json_decode (JSON → array).Array to JSON (encode)
<?php
$data = [
"name" => "Aman",
"class" => 12,
"marks" => [90, 85, 88]
];
echo json_encode($data);
?>
json_encode turns the whole array — including the nested marks array — into a single JSON string, ready to send to a browser or API.
JSON to array (decode)
Add true as the second argument to get a PHP array back.
<?php
$json = '{"name":"Aman","class":12}';
$arr = json_decode($json, true);
echo $arr["name"]; // Aman
echo $arr["class"]; // 12
?>
With true, you access values like a normal associative array ($arr["name"]).
Decode as object
Without true, PHP gives you an object; access with ->.
<?php
$json = '{"name":"Aman","class":12}';
$obj = json_decode($json); // object
echo $obj->name; // Aman
?>
Both ways work — choose array style (["name"]) or object style (->name) based on what your code prefers.
Readable JSON
Use JSON_PRETTY_PRINT to format JSON nicely for humans.
<?php
$data = ["name" => "Aman", "class" => 12];
echo json_encode($data, JSON_PRETTY_PRINT);
?>
"name": "Aman",
"class": 12
}
Pretty print adds indentation, which is great while debugging or saving JSON to a file you may read yourself.
Common mistakes
- Forgetting
truein json_decode. Without it you get an object, so$x["key"]fails. - Invalid JSON. A stray comma or missing quote makes
json_decodereturn null. - Not checking errors. Use
json_last_error_msg()to see why decoding failed. - Mixing object and array access. Use
->for objects,[]for arrays — not both.
Summary
- JSON is a text format for sending data between systems.
json_encodeturns a PHP array into JSON.json_decode($j, true)turns JSON into a PHP array.- Without
true, you get an object (use->). - Use
JSON_PRETTY_PRINTfor readable output.
Next, fetch JSON from other sites with PHP cURL, or build a data API using arrays and PHP REST API.
Frequently Asked Questions
What is JSON used for in PHP?
json_encode and reads JSON back with json_decode.What is the difference between json_encode and json_decode?
json_encode converts a PHP array or object into a JSON string. json_decode does the reverse — it turns a JSON string back into a PHP array or object. They are exact opposites.How do I get an array instead of an object from json_decode?
true as the second argument: json_decode($json, true). Without it, PHP gives you an object where you access values with -> instead of [].Why does json_decode return null?
json_last_error_msg() to see what went wrong.