What are the best practices for decoding and encoding JSON objects in PHP?
When working with JSON objects in PHP, it is important to use the built-in functions json_encode() and json_decode() to properly encode and decode data. This ensures that the data is formatted correctly and can be easily manipulated in your PHP code.
// Encoding an array into a JSON object
$data = ['name' => 'John', 'age' => 30];
$json = json_encode($data);
// Decoding a JSON object into an array
$json = '{"name": "John", "age": 30}';
$data = json_decode($json, true);
// Accessing the decoded data
echo $data['name']; // Output: John
echo $data['age']; // Output: 30