How can caching be implemented in PHP to prevent excessive API requests?
To prevent excessive API requests in PHP, caching can be implemented by storing the API response data in a cache for a certain period of time. This way, subsequent requests for the same data can be served from the cache instead of making redundant API calls.
// Check if data is cached
$cache_key = 'api_data';
$cache_duration = 3600; // Cache data for 1 hour
if ($cached_data = apc_fetch($cache_key)) {
// Use cached data
$data = $cached_data;
} else {
// Make API request
$api_response = file_get_contents('https://api.example.com/data');
// Process API response
$data = json_decode($api_response);
// Cache API response data
apc_store($cache_key, $data, $cache_duration);
}
// Use $data for further processing