What are best practices for handling JSON data in PHP scripts?

When handling JSON data in PHP scripts, it is important to properly encode and decode the data to ensure that it is formatted correctly and can be easily manipulated. Use the json_encode() function to convert PHP data structures into JSON format, and json_decode() function to convert JSON data back into PHP data structures.

// Example of encoding PHP data into JSON format
$data = array("name" => "John", "age" => 30, "city" => "New York");
$jsonData = json_encode($data);

// Example of decoding JSON data into PHP data structures
$jsonString = '{"name": "Jane", "age": 25, "city": "Los Angeles"}';
$decodedData = json_decode($jsonString, true);

// Accessing decoded JSON data
echo $decodedData['name']; // Output: Jane
echo $decodedData['age']; // Output: 25
echo $decodedData['city']; // Output: Los Angeles