What are some best practices for caching XML data in an array or external storage to improve performance and reduce the need for frequent API calls?

When dealing with XML data that requires frequent API calls, caching the data in an array or external storage can significantly improve performance by reducing the need for repeated requests to the API. One way to do this is by fetching the XML data from the API, parsing it, and then storing it in a cache such as a PHP array or a file. Subsequent requests can then retrieve the data from the cache instead of making additional API calls.

// Function to fetch and cache XML data
function get_cached_xml_data($cache_key, $api_url) {
    $cache_file = 'cache/' . $cache_key . '.xml';

    if (file_exists($cache_file) && (time() - filemtime($cache_file) < 3600)) {
        $xml_data = file_get_contents($cache_file);
    } else {
        $xml_data = file_get_contents($api_url);
        file_put_contents($cache_file, $xml_data);
    }

    return simplexml_load_string($xml_data);
}

// Example of fetching and caching XML data
$api_url = 'https://example.com/api/data.xml';
$cache_key = 'cached_data';

$xml_data = get_cached_xml_data($cache_key, $api_url);

// Process and use the XML data as needed