JSON in PHP

Why JSON in PHP?

PHP is a server-side scripting language widely used for building websites, content management systems, and REST APIs. JSON is an essential part of modern PHP development — it is used to send API responses to JavaScript clients, to receive data from mobile apps, to store structured configuration data, and to exchange information between systems.

PHP has two built-in functions for working with JSON — json_encode() and json_decode(). No library installation is needed; both are available in PHP 5.2 and above.

The Two Core JSON Functions in PHP

FunctionPurpose
json_encode()Converts a PHP array or object into a JSON string
json_decode()Converts a JSON string into a PHP array or object

1. Converting PHP to JSON — json_encode()

json_encode() takes a PHP array or object and returns it as a JSON-formatted string.

<?php
$student = array(
    "name"      => "Chitra Balan",
    "age"       => 21,
    "course"    => "Computer Science",
    "isEnrolled"=> true
);

$jsonString = json_encode($student);
echo $jsonString;
?>

// Output: {"name":"Chitra Balan","age":21,"course":"Computer Science","isEnrolled":true}

Pretty-Printing with json_encode()

Pass JSON_PRETTY_PRINT as the second argument to produce formatted, readable output:

<?php
$product = array(
    "productName" => "Solar Lantern",
    "price"       => 750,
    "inStock"     => true
);

echo json_encode($product, JSON_PRETTY_PRINT);
?>

Output:

{
    "productName": "Solar Lantern",
    "price": 750,
    "inStock": true
}

Encoding a Nested Array

<?php
$employee = array(
    "name"       => "Keshav Reddy",
    "department" => "Engineering",
    "skills"     => array("PHP", "MySQL", "REST APIs"),
    "address"    => array(
        "city"   => "Vijayawada",
        "state"  => "Andhra Pradesh"
    )
);

echo json_encode($employee, JSON_PRETTY_PRINT);
?>

Output:

{
    "name": "Keshav Reddy",
    "department": "Engineering",
    "skills": [
        "PHP",
        "MySQL",
        "REST APIs"
    ],
    "address": {
        "city": "Vijayawada",
        "state": "Andhra Pradesh"
    }
}

2. Converting JSON to PHP — json_decode()

json_decode() takes a JSON string and converts it into a PHP object (by default) or a PHP associative array (when the second argument is true).

Decoding as a PHP Object (default)

<?php
$jsonString = '{"name": "Ananya Iyer", "age": 24, "city": "Coimbatore"}';

$person = json_decode($jsonString);

echo $person->name;   // Output: Ananya Iyer
echo $person->age;    // Output: 24
echo $person->city;   // Output: Coimbatore
?>

Decoding as an Associative Array (pass true)

<?php
$jsonString = '{"name": "Ananya Iyer", "age": 24, "city": "Coimbatore"}';

$person = json_decode($jsonString, true);

echo $person["name"];   // Output: Ananya Iyer
echo $person["age"];    // Output: 24
echo $person["city"];   // Output: Coimbatore
?>

Most PHP developers prefer the associative array format (second argument true) because PHP arrays are more versatile and familiar to work with than PHP objects.

Decoding a JSON Array

<?php
$jsonString = '[{"name": "Rahul", "score": 88}, {"name": "Priti", "score": 76}]';

$students = json_decode($jsonString, true);

foreach ($students as $student) {
    echo $student["name"] . ": " . $student["score"] . "\n";
}

// Output:
// Rahul: 88
// Priti: 76
?>

Sending a JSON API Response from PHP

In real-world PHP backends, JSON is sent as an API response to a browser or mobile app. Always set the correct Content-Type header before echoing JSON:

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

$response = array(
    "status"  => "success",
    "message" => "User found",
    "user"    => array(
        "id"    => 101,
        "name"  => "Lakshmi Venkatesh",
        "email" => "lakshmi@example.com"
    )
);

echo json_encode($response);
?>

Output sent to the client:

{"status":"success","message":"User found","user":{"id":101,"name":"Lakshmi Venkatesh","email":"lakshmi@example.com"}}

Receiving JSON from a POST Request in PHP

When a JavaScript client (browser or mobile app) sends JSON data to a PHP backend using a POST request, the data is received through php://input:

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

// Read the raw JSON from the request body
$rawInput = file_get_contents("php://input");

// Decode it into an associative array
$data = json_decode($rawInput, true);

if ($data !== null) {
    $name  = $data["name"];
    $email = $data["email"];

    // Process the data (e.g., save to database)
    $response = array(
        "status"  => "success",
        "message" => "Hello, " . $name . "! Data received."
    );
} else {
    $response = array(
        "status"  => "error",
        "message" => "Invalid JSON received."
    );
}

echo json_encode($response);
?>

Handling JSON Errors in PHP

After calling json_decode() or json_encode(), always check json_last_error() to verify the operation succeeded:

<?php
$badJson = '{"name": "Raj", "age": }';  // Invalid JSON

$data = json_decode($badJson, true);

if (json_last_error() !== JSON_ERROR_NONE) {
    echo "JSON error: " . json_last_error_msg();
    // Output: JSON error: Syntax error
}
?>

PHP to JSON Data Type Mapping

PHP TypeJSON Equivalent
Associative Array (array())Object { }
Indexed Array (array())Array [ ]
stringString
int / floatNumber
true / falsetrue / false
nullnull

Key Points to Remember

  • json_encode() converts a PHP array/object to a JSON string
  • json_decode($str, true) converts a JSON string to a PHP associative array
  • Always set header("Content-Type: application/json") when returning JSON from an API
  • Use php://input to read incoming JSON data in POST requests
  • Use JSON_PRETTY_PRINT flag in json_encode() for readable output during development
  • Always check json_last_error() after decoding to detect parsing errors

Summary

PHP and JSON are a natural pairing in backend web development. With json_encode() and json_decode(), PHP can easily produce and consume JSON data — whether serving an API, processing a form submission, or exchanging data with a mobile app. These two functions are among the most frequently used tools in any PHP developer's daily work.

Leave a Comment

Your email address will not be published. Required fields are marked *