What are the best practices for minimizing unnecessary resource usage when fetching data from external websites in PHP, such as avoiding repetitive requests?
To minimize unnecessary resource usage when fetching data from external websites in PHP, one of the best practices is to cache the responses to avoid repetitive requests. By storing the fetched data locally, subsequent requests can be served from the cache instead of making additional calls to the external website.
// Check if the data is already cached
$cacheFile = 'cached_data.json';
if (file_exists($cacheFile) && time() - filemtime($cacheFile) < 3600) {
$data = file_get_contents($cacheFile);
} else {
// Fetch data from the external website
$data = file_get_contents('http://example.com/api/data');
// Save the data to cache
file_put_contents($cacheFile, $data);
}
// Process the fetched data
$dataArray = json_decode($data, true);
foreach ($dataArray as $item) {
// Do something with each item
}
Keywords
Related Questions
- What could be the potential reasons for the error message "fopen(): failed to open stream: HTTP request failed! HTTP/1.1 426 Upgrade Required" in PHP scripts?
- What are the potential pitfalls of using nested loops to generate tables in PHP?
- Are there alternative methods or best practices for validating GET data in PHP?