What are some best practices for optimizing the performance of PHP scripts that need to constantly fetch and display updated information from external sources?

To optimize the performance of PHP scripts that need to constantly fetch and display updated information from external sources, it is important to implement caching mechanisms to reduce the number of requests made to the external source. This can include storing the fetched data in a local cache and setting expiration times to refresh the data periodically. Additionally, using asynchronous requests or background processes can help improve the responsiveness of the script.

<?php

// Check if cached data is available and not expired
if(file_exists('cache.txt') && time() - filemtime('cache.txt') < 3600) {
    $data = file_get_contents('cache.txt');
} else {
    // Fetch data from external source
    $data = file_get_contents('http://example.com/data');
    
    // Store fetched data in cache
    file_put_contents('cache.txt', $data);
}

// Display the fetched data
echo $data;

?>