JSON is built on two simple structures:
- Object: A collection of key/value pairs (represented as a PHP associative array or object).
- Array: An ordered list of values (represented as a PHP indexed array).
The primary goal of JSON handling in PHP is to convert data between the PHP structure and the JSON string format.
1. PHP to JSON: Encoding (json_encode())
The json_encode() function takes a PHP array or object and converts it into a valid JSON string. This is typically done before sending data back to a client’s web browser via an API.
| Syntax | Description |
json_encode(value, options, depth) | Returns a JSON string representation of the PHP value. |
Example: Encoding Data for an API
<?php
$product_data = array(
"id" => 123,
"name" => "Wireless Headset",
"price" => 59.99,
"in_stock" => true,
"features" => ["Noise Cancellation", "Bluetooth 5.0"]
);
// Convert the PHP associative array to a JSON string
$json_output = json_encode($product_data);
// Set the content type header so the browser knows the response is JSON
header('Content-Type: application/json');
echo $json_output;
/* Example JSON Output (as a string):
{"id":123,"name":"Wireless Headset","price":59.99,"in_stock":true,"features":["Noise Cancellation","Bluetooth 5.0"]}
*/
?>
2. JSON to PHP: Decoding (json_decode())
The json_decode() function takes a JSON string and converts it back into a PHP structure (either an object or an associative array). This is typically done when receiving data from a client or an external API.
| Syntax | Description |
json_decode(json_string, associative, depth, options) | Converts the JSON string into a PHP value. |
The Crucial associative Parameter
The second parameter (associative) is the most important:
- If set to
true, JSON objects are returned as PHP associative arrays (recommended for general use). - If set to
false(the default), JSON objects are returned as generic PHP objects.
Example: Decoding Received JSON
<?php
$json_input = '{"user_id": 401, "action": "update", "timestamp": 1733000000}';
// Decode to an associative array (most common practice)
$data_array = json_decode($json_input, true);
// Decode to a PHP object
$data_object = json_decode($json_input);
echo "Array Access: User ID is " . $data_array['user_id'] . "<br>";
echo "Object Access: Action is " . $data_object->action;
// Output:
// Array Access: User ID is 401
// Object Access: Action is update
?>
3. Handling Encoding Errors
Sometimes, PHP cannot encode or decode data (e.g., trying to encode a resource, like a file handle). You should always check for errors immediately after calling json_encode() or json_decode() using json_last_error() and json_last_error_msg().
<?php
$invalid_json = '{"key": "value", "missing_quote}'; // Missing quote makes this invalid
json_decode($invalid_json);
if (json_last_error() !== JSON_ERROR_NONE) {
echo "JSON Error: " . json_last_error_msg();
}
// Output: JSON Error: Syntax error
?>
4. Encoding Options (json_encode() Flags)
You can pass various flags as the second argument of json_encode() to control the output format.
| Constant | Purpose | Example Output |
JSON_PRETTY_PRINT | Formats the output with indentation and newlines, making it human-readable. Recommended for debugging. | Output is neatly formatted. |
JSON_UNESCAPED_SLASHES | Does not escape forward slashes (/). | {"url":"http://example.com/api"} instead of http:\/\/example.com\/api |
JSON_UNESCAPED_UNICODE | Does not encode multi-byte characters (like emojis or foreign letters) as \uXXXX. | {"char":"😊"} instead of {"char":"\uD83D\uDE0A"} |
Example: Pretty Print for Debugging
<?php
$data = ["item1" => 10, "item2" => 20];
$pretty_json = json_encode($data, JSON_PRETTY_PRINT);
echo $pretty_json;
/* Output:
{
"item1": 10,
"item2": 20
}
*/
?>
