PHP JSON

JSON (JavaScript Object Notation) is a lightweight data interchange format that is easy for humans to read and write and easy for machines to parse and generate. PHP provides built-in functions for encoding and decoding JSON data.

Encoding Data to JSON

<?php
$data = array(
    "name" => "John",
    "age" => 30,
    "city" => "New York"
);
$jsonData = json_encode($data);
echo $jsonData;
?>

Output:

{"name":"John","age":30,"city":"New York"}

Explanation: This example demonstrates how to encode a PHP array into a JSON string using the json_encode() function.

Decoding JSON Data

<?php
$jsonString = '{"name":"John","age":30,"city":"New York"}';
$data = json_decode($jsonString, true);
print_r($data);
?>

Output:

Array
(
    [name] => John
    [age] => 30
    [city] => New York
)

Explanation: This example demonstrates how to decode a JSON string back into a PHP associative array using the json_decode() function. The second parameter is set to true to return an associative array.

Handling JSON Errors

<?php
$jsonString = '{"name":"John", "age":30'; // Invalid JSON
$data = json_decode($jsonString);
if (json_last_error() !== JSON_ERROR_NONE) {
    echo "JSON Error: " . json_last_error_msg();
}
?>

Explanation: This example shows how to check for JSON errors after decoding a JSON string. The json_last_error() function returns the last error occurred, and json_last_error_msg() provides a human-readable error message.

JSON Pretty Print

<?php
$data = array(
    "name" => "John",
    "age" => 30,
    "city" => "New York"
);
$jsonData = json_encode($data, JSON_PRETTY_PRINT);
echo $jsonData;
?>

Output:

{
    "name": "John",
    "age": 30,
    "city": "New York"
}

Explanation: This example demonstrates how to pretty print JSON data using the JSON_PRETTY_PRINT option in the json_encode() function.