📡 You're offline — showing cached content
New version available!
Quick Access
PHP Beginner

PHP JSON: Encode, Decode, and Work with APIs

Learn json_encode, json_decode, building JSON API responses, and calling APIs with cURL.

EzyCoders Admin May 26, 2026 2 min read 7 views
PHP JSON: Encode, Decode, and Work with APIs
Share: Twitter LinkedIn WhatsApp

What is it?

JSON (JavaScript Object Notation) is the universal format for data exchange between systems. PHP makes converting between PHP arrays and JSON trivially easy with two functions.

Why does it matter?

Modern applications communicate through APIs — payment gateways, SMS services, maps, weather data. All of them speak JSON. Knowing how to encode, decode, and error-check JSON is essential.

Learn json_encode, json_decode, building JSON API responses, and calling APIs with cURL.

Real-World Use Cases

  • 💳 Payment gateway integration - Decode the JSON response from Razorpay or Stripe to check payment status and extract transaction IDs.
  • 📱 Mobile app backend - Build a REST API endpoint that returns JSON — the mobile app reads it to display products, users, and orders.
  • 🌐 Third-party API calls - Call OpenWeatherMap or Google Maps APIs, decode the JSON response, and display data in your PHP page.
  • ⚙️ Configuration files - Store app settings in a JSON file, read with file_get_contents, and decode to an associative array.

json_encode and json_decode

// PHP Array
$data = [
    "name" => "Shivom",
    "city" => "Pune"
];

// Array to JSON
$json = json_encode($data);

echo $json;


// JSON to PHP Array
$array = json_decode($json, true);

echo $array['name'];

Building a JSON API Response

// JSON API Response
header("Content-Type: application/json");

echo json_encode([
    "status" => true,
    "message" => "Success"
]);

Calling an External API with cURL

// Calling External API using cURL
$ch = curl_init("https://jsonplaceholder.typicode.com/users/1");

curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$response = curl_exec($ch);

curl_close($ch);

// Convert API JSON response to PHP array
$result = json_decode($response, true);

print_r($result);

Q: Why does json_decode return null sometimes?

json_decode returns null for invalid JSON. Always check json_last_error() === JSON_ERROR_NONE. Common causes: trailing commas, single quotes instead of double, or an HTML error page returned instead of JSON.

EzyCoders Admin
Written by
EzyCoders Admin

Team Lead and Full-Stack Developer with experience in PHP, JavaScript, SQL, DSA, and System Design. Passionate about software engineering, scalable web technologies, and helping developers prepare for coding interviews and tech careers through practical tutorials and professional guidance.

Comments (0)

No comments yet. Be the first!

Leave a Comment