PHP JSON
advancedPart of PHP Data & APIs
Theory
JSON (JavaScript Object Notation) is the most common data format for web APIs. PHP provides built-in functions to encode and decode JSON.
json_encode and json_decode
$array = ["name" => "Alice", "age" => 25, "skills" => ["PHP", "JavaScript"]];
// Convert PHP array to JSON string
$json = json_encode($array);
echo $json;
// {"name":"Alice","age":25,"skills":["PHP","JavaScript"]}
// Convert JSON string back to PHP array
$decoded = json_decode($json, true); // true = associative array
echo $decoded["name"]; // AliceThe second parameter of json_decode() controls the return type:
true— returns an associative arrayfalse(default) — returns a stdClass object
JSON Flags
json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);Common flags: JSON_PRETTY_PRINT, JSON_UNESCAPED_UNICODE, JSON_UNESCAPED_SLASHES, JSON_FORCE_OBJECT.
Fetching Data with file_get_contents
For simple GET requests:
$response = file_get_contents("https://api.example.com/data");
$data = json_decode($response, true);Fetching Data with cURL
For more control (POST, headers, authentication):
cURL and JSON API Example
phpError Handling
$json = '{"name": "Alice", age: 25}'; // Invalid JSON
$data = json_decode($json, true);
if (json_last_error() !== JSON_ERROR_NONE) {
echo "JSON Error: " . json_last_error_msg();
}Practical Examples
Example: JSON CRUD Operations
phpExercises
Fetch and Display Posts from JSON API
Use file_get_contents to fetch posts from JSONPlaceholder API (https://jsonplaceholder.typicode.com/posts?userId=1). Decode the JSON and display each post's title and body in an HTML list.
Expected Output:
An HTML page listing post titles and bodies fetched from the API