JSON is everywhere. APIs send JSON, configuration files use JSON, and modern frontend frameworks expect JSON. PHP makes it stupidly easy to convert between JSON and PHP arrays or objects with just two functions: json_encode() and json_decode().
json_encode โ Converting PHP to JSON
Turn a PHP array or object into a JSON string with json_encode(). It automatically handles nested arrays, strings, numbers, and booleans. Add JSON_PRETTY_PRINT as a second argument to get nicely formatted output โ great for debugging.
<?php
$user = [
"name" => "Alice",
"age" => 30,
"skills" => ["PHP", "JavaScript", "MySQL"]
];
echo json_encode($user, JSON_PRETTY_PRINT);
?>
Try it Yourself โ
json_decode โ Converting JSON to PHP
Take a JSON string and turn it back into a PHP object or array. By default, json_decode() returns objects. Pass true as the second argument to get associative arrays instead.
<?php
$json = '{"name":"Alice","age":30,"city":"New York"}';
$data = json_decode($json, true);
echo $data["name"];
echo $data["city"];
?>
Try it Yourself โ
Working with API Data
Real-world APIs return JSON. You can grab that data with file_get_contents() and decode it with json_decode(). It's a two-step process that opens up the entire world of web APIs โ weather data, GitHub stats, movie info, you name it.