What are some best practices for handling JSON objects and arrays in PHP when working with APIs?

When working with APIs that return JSON data in PHP, it is important to properly handle JSON objects and arrays to extract the necessary information. One best practice is to use the json_decode function to convert the JSON data into a PHP array or object, making it easier to work with. Additionally, it is crucial to check for any errors during the decoding process to ensure the data is valid before further processing.

// Sample code to handle JSON data from an API response
$jsonData = '{"name": "John Doe", "age": 30, "city": "New York"}';

// Decode the JSON data into a PHP associative array
$decodedData = json_decode($jsonData, true);

// Check for decoding errors
if (json_last_error() !== JSON_ERROR_NONE) {
    die("Error decoding JSON data: " . json_last_error_msg());
}

// Access the data from the decoded array
echo "Name: " . $decodedData['name'] . "\n";
echo "Age: " . $decodedData['age'] . "\n";
echo "City: " . $decodedData['city'] . "\n";