PHP JSON
Working with JSON data in PHP
📦 What is PHP JSON?
JSON (JavaScript Object Notation) is a lightweight data format. PHP provides built-in functions to encode and decode JSON data, making it easy to exchange information between servers and web applications.
<?php
// Simple JSON example
$data = array("name" => "John", "age" => 30);
echo json_encode($data);
?>
Output:
{"name":"John","age":30}
Key JSON Functions
json_encode()
Convert PHP data to JSON format
<?php
$arr = ["a", "b", "c"];
echo json_encode($arr);
?>
json_decode()
Convert JSON to PHP data
<?php
$json = '{"name":"Alice"}';
$obj = json_decode($json);
echo $obj->name;
?>
json_last_error()
Check for JSON errors
<?php
json_decode("invalid");
if(json_last_error() != 0) {
echo "Error!";
}
?>
json_validate()
Validate JSON strings (PHP 8.3+)
<?php
$valid = json_validate('{"a":1}');
echo $valid ? "Valid" : "Invalid";
?>
🔹 Encoding PHP Arrays to JSON
The json_encode() function converts PHP arrays and objects into JSON strings. This is useful when sending data to JavaScript or APIs.
<?php
// Indexed array
$colors = array("red", "green", "blue");
echo json_encode($colors);
echo "\n\n";
// Associative array
$person = array(
"name" => "Sarah",
"age" => 25,
"city" => "New York"
);
echo json_encode($person);
?>
Output:
["red","green","blue"]
{"name":"Sarah","age":25,"city":"New York"}
🔹 Decoding JSON to PHP
The json_decode() function converts JSON strings back into PHP variables. Use the second parameter to get an associative array instead of an object.
<?php
$json = '{"name":"Mike","age":28,"skills":["PHP","MySQL"]}';
// Decode as object
$obj = json_decode($json);
echo "Name: " . $obj->name . "\n";
echo "Age: " . $obj->age . "\n";
echo "\n";
// Decode as array
$arr = json_decode($json, true);
echo "Name: " . $arr["name"] . "\n";
echo "Skills: " . implode(", ", $arr["skills"]);
?>
Output:
Age: 28
Name: Mike
Skills: PHP, MySQL
🔹 JSON Encoding Options
PHP provides various options to format JSON output. These flags help make JSON more readable or handle special characters properly.
<?php
$data = array(
"name" => "José",
"url" => "https://example.com/path",
"price" => 19.99
);
// Pretty print
echo json_encode($data, JSON_PRETTY_PRINT);
echo "\n\n";
// Unescaped unicode and slashes
echo json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
?>
Output:
{
"name": "José",
"url": "https://example.com/path",
"price": 19.99
}
{"name":"José","url":"https://example.com/path","price":19.99}
🔹 Handling JSON Errors
Always check for errors when working with JSON. PHP provides functions to detect and handle JSON parsing errors gracefully.
<?php
// Invalid JSON
$invalid_json = '{"name": "John", "age": }';
$result = json_decode($invalid_json);
if (json_last_error() !== JSON_ERROR_NONE) {
echo "JSON Error: " . json_last_error_msg();
} else {
echo "JSON is valid!";
}
?>
Output:
🔹 Working with Nested JSON
JSON can contain nested objects and arrays. PHP handles multi-level data structures easily with json_encode() and json_decode().
<?php
// Create nested structure
$company = array(
"name" => "Tech Corp",
"employees" => array(
array("name" => "Alice", "role" => "Developer"),
array("name" => "Bob", "role" => "Designer")
)
);
$json = json_encode($company, JSON_PRETTY_PRINT);
echo $json;
echo "\n\n";
// Access nested data
$decoded = json_decode($json, true);
echo "First employee: " . $decoded["employees"][0]["name"];
?>
Output:
{
"name": "Tech Corp",
"employees": [
{"name": "Alice", "role": "Developer"},
{"name": "Bob", "role": "Designer"}
]
}
First employee: Alice
🔹 Reading JSON from Files
You can read JSON data from external files and parse it into PHP. This is common when working with configuration files or data storage.
<?php
// Read JSON file
$json_string = file_get_contents('data.json');
$data = json_decode($json_string, true);
// Access data
echo "Name: " . $data["name"];
// Write JSON to file
$new_data = array("status" => "active", "count" => 42);
file_put_contents('output.json', json_encode($new_data, JSON_PRETTY_PRINT));
?>
Common Use Cases:
- API responses and requests
- Configuration files
- Data exchange between PHP and JavaScript
- Storing structured data