How can caching be used in PHP to improve performance when retrieving data from external sources?
Caching can be used in PHP to improve performance when retrieving data from external sources by storing the results in a cache for future use. This reduces the need to make repeated requests to the external source, resulting in faster response times and reduced load on the external server.
// Check if data is already cached
$cacheKey = 'external_data';
if ($cachedData = apc_fetch($cacheKey)) {
$data = $cachedData;
} else {
// Make request to external source
$data = fetchDataFromExternalSource();
// Cache the data for future use
apc_store($cacheKey, $data, 3600); // Cache for 1 hour
}
// Use the retrieved data
echo $data;