What are best practices for handling API responses in PHP?

When handling API responses in PHP, it is important to properly handle errors and parse the response data. One common best practice is to check the HTTP status code of the response to determine if the request was successful or not. Additionally, it is recommended to use JSON decoding functions to extract data from the response.

// Example of handling API response in PHP
$response = file_get_contents('https://api.example.com/data');
$http_status = substr($http_response_header[0], 9, 3); // Get HTTP status code

if ($http_status == 200) {
    $data = json_decode($response, true); // Parse JSON response
    // Process the data accordingly
} else {
    // Handle error based on HTTP status code
    echo "Error: HTTP status code $http_status";
}