How can caching be implemented effectively when working with XML files in PHP?

When working with XML files in PHP, caching can be implemented effectively by storing the parsed XML data in a cache like Memcached or Redis. This helps reduce the overhead of repeatedly parsing the XML file, improving performance and response times.

// Check if the parsed XML data is already cached
$cacheKey = 'xml_data';
$cache = new Memcached();
$cache->addServer('localhost', 11211);

$xmlData = $cache->get($cacheKey);

// If data is not cached, parse the XML file and store it in the cache
if (!$xmlData) {
    $xml = simplexml_load_file('data.xml');
    $xmlData = json_encode($xml);
    
    $cache->set($cacheKey, $xmlData, 3600); // Cache for 1 hour
}

// Use the cached XML data
$data = json_decode($xmlData, true);