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;
Keywords
Related Questions
- What is the significance of using round brackets in regular expressions when using preg_match_all in PHP, and how can they help in capturing specific parts of the text?
- What are some potential pitfalls of working with a PHP script that lacks structure and documentation?
- What are common pitfalls when trying to implement a secure download feature in PHP?