JSON PHP

Working with JSON data in PHP applications

🐘 What is JSON PHP?

JSON PHP refers to using JSON data format with PHP programming language. PHP provides built-in functions to encode PHP data to JSON and decode JSON data back to PHP variables.


<?php
// PHP array to JSON
$data = array("name" => "John", "age" => 30);
$json = json_encode($data);
echo $json; // {"name":"John","age":30}
?>
                                    

PHP to JSON (json_encode)

📝

Arrays to JSON

Convert PHP arrays to JSON format

🔧

Objects to JSON

Convert PHP objects to JSON strings

⚙️

Options & Flags

Control JSON output formatting

🔹 Converting PHP Array to JSON

Use json_encode() to convert PHP data to JSON:

<?php
// Simple array
$fruits = array("apple", "banana", "orange");
$json_fruits = json_encode($fruits);
echo $json_fruits;

// Associative array
$person = array(
    "name" => "Alice",
    "age" => 25,
    "city" => "New York"
);
$json_person = json_encode($person);
echo $json_person;
?>

Output:

["apple","banana","orange"]

{"name":"Alice","age":25,"city":"New York"}

🔹 JSON to PHP (json_decode)

Use json_decode() to convert JSON back to PHP:

<?php
// JSON string
$json_data = '{"name":"Bob","age":30,"skills":["PHP","JavaScript","MySQL"]}';

// Decode to associative array
$array_data = json_decode($json_data, true);
echo $array_data['name']; // Bob

// Decode to object
$object_data = json_decode($json_data);
echo $object_data->name; // Bob
?>

Output:

Bob

Bob

🔹 Real-World Example: API Response

Common use case - handling API data in PHP:

<?php
// Simulate API response
$api_response = '{
    "status": "success",
    "data": {
        "users": [
            {"id": 1, "name": "John", "email": "[email protected]"},
            {"id": 2, "name": "Jane", "email": "[email protected]"}
        ]
    }
}';

// Process the JSON
$response = json_decode($api_response, true);

if ($response['status'] === 'success') {
    foreach ($response['data']['users'] as $user) {
        echo "User: " . $user['name'] . " (" . $user['email'] . ")\n";
    }
}
?>

Output:

User: John ([email protected])

User: Jane ([email protected])

🔹 Error Handling

Always check for JSON errors in production code:

<?php
$invalid_json = '{"name": "John", "age": }'; // Invalid JSON

$data = json_decode($invalid_json, true);

if (json_last_error() !== JSON_ERROR_NONE) {
    echo "JSON Error: " . json_last_error_msg();
} else {
    echo "Data processed successfully";
}
?>

Output:

JSON Error: Syntax error

🧠 Test Your Knowledge

Which PHP function converts an array to JSON?