Free tutorials & notes in Hindi & English · Clean code examples 🧰 Free PDF & Image Tools →
🔴 Advanced  ·  Lesson 31

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.

💡 PHP has two key functions: 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);
?>
{"name":"Aman","class":12,"marks":[90,85,88]}

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
?>
Aman 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
?>
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 true in json_decode. Without it you get an object, so $x["key"] fails.
  • Invalid JSON. A stray comma or missing quote makes json_decode return 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_encode turns 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_PRINT for 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 is a simple text format for sending data between systems — for example between PHP and JavaScript, or when building an API. PHP turns arrays into JSON with 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?
Pass 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?
Usually the JSON is invalid — a missing quote, comma, or bracket. Check the error with json_last_error_msg() to see what went wrong.
Can json_encode handle nested arrays?
Yes. Nested arrays become nested JSON automatically, so a multidimensional PHP array turns into JSON objects inside objects without any extra work.
← Back to PHP Tutorial
🔗

Share this topic with a friend

यह topic किसी दोस्त को भेजें

Found it useful? Send it to a classmate learning the same thing.

अच्छा लगा? जो दोस्त यही सीख रहा है, उसे भेज दीजिए।

💻 Live Code Editor

This page's programs are ready here — run them, edit them, and learn. No installation needed.
Powered by OneCompiler. The code loads into the editor automatically — press Run to see the output. If the editor does not open, open it in a new tab.
Next topiccURL API Requests Your progress: 31 / 50 (62%) · Lesson 32 / 50 Continue →

How was this lesson?

Your feedback helps us make the content better.

Write a review or suggestion (optional)

After approval, your name and city may appear publicly with your review. Please do not write your email or phone number.

▶ CodingEasily on YouTube

Learn with video lessons in easy Hindi

Featured video: RDBMS Part 3 – Class XI Commerce IT

▶ Subscribe – it’s free