Docs/PHP/JSON

PHP JSON

Functions

  • json_encode($data) — PHP → JSON string
  • json_decode($json) — JSON string → PHP object
  • json_decode($json, true) — JSON → associative array
index.php
Try It →
<?php
$user = [
    "name" => "Ali",
    "age" => 25,
    "skills" => ["PHP", "MySQL", "JS"],
    "active" => true
];

// Encode
$json = json_encode($user, JSON_PRETTY_PRINT);
echo "PHP Array → JSON:
$json

";

// Decode to object
$obj = json_decode($json);
echo "JSON → Object: " . $obj->name . "
";

// Decode to array
$arr = json_decode($json, true);
echo "JSON → Array: " . $arr["name"] . "
";
echo "Skills: " . implode(", ", $arr["skills"]) . "

";

// API response pattern
$response = json_encode([
    "status" => "success",
    "data" => $user,
    "timestamp" => date("c")
], JSON_PRETTY_PRINT);
echo "API Response:
$response";
?>