PHP JSON Handling

πŸ“¦ PHP JSON Handling – Encode & Decode JSON Data

JSON (JavaScript Object Notation) is a **lightweight data format** used for **data exchange** between systems. It’s widely used in APIs, web applications, and more.

In PHP, we use json_encode() to convert data into JSON format and json_decode() to convert JSON back into PHP data structures.


πŸš€ Encoding PHP Data to JSON

The json_encode() function converts PHP arrays or objects into a JSON string.

βœ… Example: Convert PHP Array to JSON

Let’s encode an array of fruits into JSON format.

<?php
$fruits = array("Apple", "Banana", "Cherry");

$jsonData = json_encode($fruits);

echo $jsonData;
?>

Try It Now

πŸ” Output:
["Apple","Banana","Cherry"] (JSON format!)


πŸ“– Decoding JSON to PHP

The json_decode() function converts a JSON string back into a PHP array or object.

βœ… Example: Convert JSON to PHP Array

Let’s decode JSON data into a PHP array.

<?php
$jsonData = '["Apple","Banana","Cherry"]';

$phpArray = json_decode($jsonData, true);

print_r($phpArray);
?>

Try It Now

πŸ” Output:

Array
(
    [0] => Apple
    [1] => Banana
    [2] => Cherry
)

Passing true as the second parameter makes it return an **associative array** instead of an object.


πŸ“ Encoding & Decoding PHP Objects

JSON also works with PHP objects. Let’s convert a PHP object to JSON and back.

βœ… Example: Convert PHP Object to JSON

<?php
class Fruit {
    public $name;
    public $color;
}

$apple = new Fruit();
$apple->name = "Apple";
$apple->color = "Red";

$jsonData = json_encode($apple);

echo $jsonData;
?>

Try It Now

πŸ” Output:
{"name":"Apple","color":"Red"}

βœ… Example: Convert JSON to PHP Object

<?php
$jsonData = '{"name":"Apple","color":"Red"}';

$phpObject = json_decode($jsonData);

echo "Fruit: " . $phpObject->name . ", Color: " . $phpObject->color;
?>

Try It Now

πŸ” Output:
Fruit: Apple, Color: Red


πŸ”§ Handling JSON Errors

If JSON encoding or decoding fails, you can check for errors using json_last_error().

βœ… Example: Detect JSON Errors

<?php
$invalidJson = "{name: 'Apple', color: 'Red'}"; // Missing quotes around keys

$jsonData = json_decode($invalidJson);

if (json_last_error() !== JSON_ERROR_NONE) {
    echo "❌ JSON Error: " . json_last_error_msg();
}
?>

Try It Now

πŸ” Output:
❌ JSON Error: Syntax error


🎯 Best Practices for JSON Handling

  • βœ… Always validate JSON with json_last_error().
  • βœ… Use json_encode() for PHP β†’ JSON conversion.
  • βœ… Use json_decode() with true for arrays.
  • βœ… Ensure JSON strings use **double quotes** around keys.
  • βœ… Secure JSON data before processing it in APIs.

πŸš€ Next Steps

Now that you understand PHP JSON handling, try using it in **APIs, file storage, or AJAX calls**! Happy coding! πŸŽ‰