PHP and JSON: Encode, Decode, and Handle JSON Data

JSON (JavaScript Object Notation) is a lightweight data format that’s perfect for exchanging information between a client and a server—and it plays especially well with PHP. Whether you’re working on an API, handling AJAX requests, or storing structured data, PHP provides easy functions to encode and decode JSON.

Encode PHP Data to JSON

To convert PHP arrays or objects into JSON strings, use the json_encode() function.

Example:

<?php
$user = [
  "name" => "Alice",
  "age" => 25,
  "email" => "alice@example.com"
];

$json = json_encode($user);
echo $json;
// Output: {"name":"Alice","age":25,"email":"alice@example.com"}
?>

You can also use JSON_PRETTY_PRINT for better readability:

<?php
You can also use JSON_PRETTY_PRINT for better readability:
?>

Decode JSON to PHP

To convert a JSON string into a PHP variable, use json_decode().

Example (As Object):

<?php
$json = '{"name":"Bob","age":30,"email":"bob@example.com"}';

$data = json_decode($json);
echo $data->name; // Output: Bob
?>

Example (As Array):
Pass true as the second parameter to get an associative array:

<?php

$data = json_decode($json, true);
echo $data['email']; // Output: bob@example.com

?>

Handling JSON in API Requests
When working with APIs or JavaScript (AJAX), you’ll often receive raw JSON. Here’s how you handle that in PHP:

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

// Decode JSON to array
$data = json_decode($input, true);

echo "Name received: " . $data['name'];
?>

Common Use Cases

1) Send JSON to JavaScript: echo json_encode($data);
2) Receive JSON via fetch() or Axios from the frontend
3) Store structured settings or logs in JSON format
4) Build REST APIs that return JSON responses

Error Handling

Always check for decoding errors with json_last_error():

<?php
if (json_last_error() !== JSON_ERROR_NONE) {
    echo "JSON Error: " . json_last_error_msg();
}
?>

Summary

1) Use json_encode() to send PHP data as JSON.
2) Use json_decode() to parse JSON into PHP arrays or objects.
3) Perfect for APIs, AJAX, and frontend-backend communication.
4) Always validate and sanitize incoming data.

JSON is simple yet powerful, and with PHP, it takes just a few lines to integrate it into your project. Whether you’re building modern web apps or connecting APIs, knowing how to handle JSON is a must.

Read Also:
How to Create a Simple Form and Handle Form Data in PHP

How to Connect PHP with MySQL Database

Also Visit:
https://inimisttech.com/

Leave a Reply