How can error handling be improved in the provided PHP script to handle API response errors?

The issue with the current PHP script is that it does not handle API response errors effectively, which can lead to unexpected behavior or crashes. To improve error handling, we can check for HTTP status codes in the API response and handle different error scenarios accordingly. This can include displaying a user-friendly error message or logging the error for debugging purposes.

// Make API request
$response = file_get_contents('https://api.example.com/data');
$http_status = substr($http_response_header[0], 9, 3);

// Check for HTTP status code
if ($http_status == 200) {
    // API request was successful
    $data = json_decode($response, true);
    // Process API response data
} else {
    // Handle API response error
    if ($http_status == 404) {
        echo "Error: Resource not found";
    } else {
        echo "Error: API request failed with status code $http_status";
    }
}