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
}