JavaScript

JavaScript is a high-level, interpreted programming language that is widely used for web development. Initially designed as a client-side scripting language, it runs directly in web browsers, enabling dynamic and interactive user experiences. JavaScript can now be used for server-side development as well.

JSON with PHP

15 April 2025 | Category:

JSON (JavaScript Object Notation) is a lightweight data format used for data exchange between server and client. In PHP, you can encode PHP data to JSON and decode JSON data to PHP.

✅ JSON is commonly used when sending/receiving data in APIs, especially in AJAX or RESTful apps.


🔁 PHP and JSON Conversion Functions

FunctionPurpose
json_encode()Converts PHP data to JSON string
json_decode()Converts JSON string to PHP data

🔹 1. Encoding PHP Data to JSON

➤ Example 1: Encode an Associative Array

<?php
$data = array("name" => "Alice", "age" => 25, "city" => "Delhi");
$jsonData = json_encode($data);
echo $jsonData;
?>

✅ Output:

{"name":"Alice","age":25,"city":"Delhi"}

➤ Example 2: Encode a Multidimensional Array

<?php
$users = array(
  array("id" => 1, "name" => "Alice"),
  array("id" => 2, "name" => "Bob")
);

echo json_encode($users);
?>

✅ Output:

[
  {"id":1,"name":"Alice"},
  {"id":2,"name":"Bob"}
]

🔹 2. Decoding JSON to PHP

➤ Example: Decode JSON to Associative Array

<?php
$json = '{"name":"Alice","age":25,"city":"Delhi"}';

$phpArray = json_decode($json, true); // true returns associative array
print_r($phpArray);
?>

✅ Output:

Array
(
    [name] => Alice
    [age] => 25
    [city] => Delhi
)

➤ Decode JSON to PHP Object

<?php
$json = '{"name":"Alice","age":25}';

$phpObject = json_decode($json); // default returns object
echo $phpObject->name;
?>

✅ Output:

Alice

🔒 Handling JSON Errors

You can check for errors using:

<?php
$data = "\xB1\x31"; // Invalid UTF-8

json_encode($data);

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

🌐 JSON with PHP in AJAX Requests

➤ Example: Returning JSON from PHP (for frontend use)

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

$data = array("status" => "success", "message" => "Data fetched!");
echo json_encode($data);
?>

This PHP file can be called using AJAX from JavaScript and used like an API.


✅ Summary

TaskFunction Used
Encode PHP to JSONjson_encode()
Decode JSON to PHPjson_decode()
Error Handlingjson_last_error()
AJAX ResponsesUse header() + json_encode()

📦 Real Use Case

A sample AJAX + PHP + JSON setup:

// JavaScript (frontend)
fetch("data.php")
  .then(res => res.json())
  .then(data => {
    console.log(data.message);
  });
// data.php
<?php
header("Content-Type: application/json");
echo json_encode(["message" => "Hello from PHP!"]);
?>