JavaScript

coding learning websites codepractice

JS Basics

JS Variables & Operators

JS Data Types & Conversion

JS Numbers & Math

JS Strings

JS Dates

JS Arrays

JS Control Flow

JS Loops & Iteration

JS Functions

JS Objects

JS Classes & Modules

JS Async Programming

JS Advanced

JS HTML DOM

JS BOM (Browser Object Model)

JS Web APIs

JS AJAX

JS JSON

JS Graphics & Charts

JSON PHP


JSON is widely used to exchange data between a client (like a web browser) and a server. In PHP, JSON is fully supported, making it easy to encode PHP data into JSON for sending to a client or decode JSON received from a client.

Why JSON with PHP?

PHP is a server-side language, and when building APIs or dynamic web applications, you often need to send data in JSON format. JSON is lightweight, human-readable, and compatible with JavaScript, making it ideal for web communication.

  • Encode PHP arrays or objects into JSON.

  • Decode JSON strings into PHP arrays or objects.

  • Communicate with front-end applications using AJAX or fetch APIs.

JSON Encoding in PHP

To convert PHP data into JSON, you use the built-in function json_encode().

Example 1: PHP Array to JSON

<?php
$user = array(
    "name" => "Vicky",
    "age" => 28,
    "isDeveloper" => true
);

$jsonData = json_encode($user);
echo $jsonData;
?>

Output:

{"name":"Vicky","age":28,"isDeveloper":true}

Explanation:

  • json_encode() converts a PHP associative array into a JSON string.

  • This JSON can now be sent to a browser or stored in a file.

Example 2: PHP Object to JSON

<?php
class User {
    public $name;
    public $age;
    public $isDeveloper;

    function __construct($name, $age, $isDeveloper) {
        $this->name = $name;
        $this->age = $age;
        $this->isDeveloper = $isDeveloper;
    }
}

$user = new User("Sanjana", 26, false);
echo json_encode($user);
?>

Output:

{"name":"Sanjana","age":26,"isDeveloper":false}
  • PHP objects are automatically converted into JSON objects.

JSON Decoding in PHP

To convert JSON received from a client into PHP data, use json_decode().

Example 1: Decode JSON into PHP Array

<?php
$jsonString = '{"name":"Vicky","age":28,"isDeveloper":true}';
$user = json_decode($jsonString, true); // true converts it into an associative array

echo $user["name"]; // Output: Vicky

Example 2: Decode JSON into PHP Object

<?php
$jsonString = '{"name":"Sanjana","age":26,"isDeveloper":false}';
$user = json_decode($jsonString); // default is object

echo $user->name; // Output: Sanjana
  • The second parameter of json_decode() determines whether the result is an associative array (true) or an object (false or default).

Working with JSON Arrays

You can encode and decode arrays of data as well.

Example: Array of Users

<?php
$users = array(
    array("name" => "Vicky", "age" => 28),
    array("name" => "Sanjana", "age" => 26)
);

echo json_encode($users);
?>

Output:

[
  {"name":"Vicky","age":28},
  {"name":"Sanjana","age":26}
]

Decoding this JSON back into PHP:

<?php
$jsonString = '[{"name":"Vicky","age":28},{"name":"Sanjana","age":26}]';
$users = json_decode($jsonString, true);

foreach ($users as $user) {
    echo $user["name"] . "\n";
}

Output:

Vicky
Sanjana

Sending JSON from PHP to Client

When sending JSON data via PHP to a browser or front-end application, set the correct header:

<?php
header('Content-Type: application/json');

$data = array("message" => "Hello from PHP", "status" => true);
echo json_encode($data);
?>
  • header('Content-Type: application/json') tells the browser that the response is in JSON format.

  • This is important when using AJAX or fetch to receive data.

Receiving JSON Data in PHP

Front-end applications often send JSON via POST requests. You can read and decode it in PHP:

<?php
// Read raw POST data
$jsonData = file_get_contents("php://input");

// Convert JSON to PHP array
$data = json_decode($jsonData, true);

echo "Hello, " . $data["name"];
?>

If a front-end sends this JSON:

{"name":"Vicky","age":28}

The output will be:

Hello, Vicky

Real-World Example: Simple API with PHP

Suppose you want to create a simple API endpoint that returns users:

<?php
header('Content-Type: application/json');

$users = array(
    array("id" => 1, "name" => "Vicky", "age" => 28),
    array("id" => 2, "name" => "Sanjana", "age" => 26)
);

echo json_encode($users);
?>

From the front-end, you can fetch the data:

fetch("users.php")
  .then(response => response.json())
  .then(data => console.log(data));

Output in console:

[
  {"id":1,"name":"Vicky","age":28},
  {"id":2,"name":"Sanjana","age":26}
]

Tips When Working with JSON in PHP

  1. Always set the header to application/json for API responses.

  2. Validate JSON when decoding to avoid errors:

$data = json_decode($jsonString, true);
if (json_last_error() !== JSON_ERROR_NONE) {
    echo "Invalid JSON";
}
  1. Use associative arrays if you prefer working with array syntax ($data['name']) instead of object syntax ($data->name).

  2. Encode PHP objects carefully; private properties are not included by default.

Summary of the Tutorial

  • json_encode() converts PHP arrays or objects into JSON strings.

  • json_decode() converts JSON strings into PHP arrays or objects.

  • Set Content-Type: application/json when sending JSON to clients.

  • JSON arrays and objects are fully supported.

  • PHP and JSON work together seamlessly for API development, front-end integration, and AJAX communication.

  • Always validate and handle errors when decoding JSON from clients.

JSON in PHP makes it easy to build APIs, exchange data, and integrate front-end applications without complications.


Practice Questions

  1. Create a PHP associative array with keys name, age, and isDeveloper. Convert it to JSON using json_encode() and print it.

  2. Create a PHP object for a user with name, age, and city. Convert the object to JSON and print it.

  3. Decode this JSON string into a PHP associative array and print the name:

'{"name":"Sanjana","age":26,"isDeveloper":false}'
  1. Decode the same JSON string into a PHP object and print the age using object syntax.

  2. Create a PHP array of two users (each user is an associative array with name and age) and encode it into a JSON array.

  3. Write a PHP script that reads JSON from a POST request using file_get_contents("php://input") and prints a greeting using the name key.

  4. Set the header to application/json and send a JSON response with a status and message key.

  5. Decode a JSON array of users and loop through it to print each user’s name. Example JSON:

'[{"name":"Vicky","age":28},{"name":"Sanjana","age":26}]'
  1. Create a PHP script that validates a JSON string using json_last_error() and prints "Valid JSON" or "Invalid JSON".

  2. Encode a nested PHP array containing a user and their address (city and zipcode) into JSON and print the result.


JavaScript

online coding class codepractice

JS Basics

JS Variables & Operators

JS Data Types & Conversion

JS Numbers & Math

JS Strings

JS Dates

JS Arrays

JS Control Flow

JS Loops & Iteration

JS Functions

JS Objects

JS Classes & Modules

JS Async Programming

JS Advanced

JS HTML DOM

JS BOM (Browser Object Model)

JS Web APIs

JS AJAX

JS JSON

JS Graphics & Charts

Go Back Top