首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >php simplexml对象缓存

php simplexml对象缓存
EN

Stack Overflow用户
提问于 2011-10-18 01:05:47
回答 2查看 3K关注 0票数 1

考虑以下函数原型,用于缓存来自缓存的RSS(XML)提要的对象:

代码语言:javascript
复制
function cacheObject($xml,$name,$age = 3600)
  { 
    // directory in which to store cached files
    $cacheDir = "cache/";
    // cache filename
    $filename = $cacheDir.$name;
    // default to fetch the file
    $cache = true;
    // but if the file exists, don't fetch if it is recent enough
    if (file_exists($filename))
    {
      $cache = (filemtime($filename) < (time()-$age));
    }
    // fetch the file if required
    if ($cache)
    {
      $item = $xml->channel->item;
      file_put_contents($filename,serialize($item));
      // update timestamp to now
      touch($filename);
    }
    // return the cache filename
    return unserialize(file_get_contents($filename));
  }   

函数调用如下:

代码语言:javascript
复制
$urlD = "http://somerss.php";
    $xmlD = simplexml_load_file(cacheFetch($urlD,'cachedfeedD.xml',3600));
    $itemD = '';
    if($xmlD === FALSE)
        {$itemD = '';}
    else
        {$itemD = cacheObject($xmlD,'cacheobjectD',3600);}
 $urlM = "somerss2.php";
    $xmlM = simplexml_load_file(cacheFetch($urlM,'cachedfeedM.xml',3600));
    $itemM = '';
    if($xmlM ===  FALSE) 
        {$itemM = '';}
    else
        {$itemM = cacheObject($xmlM,'cacheobjectM',3600);}

我得到以下错误:

代码语言:javascript
复制
    Fatal error: Uncaught exception 'Exception' 
with message 'Serialization of 'SimpleXMLElement' is not allowed' in C:\xampp\htdocs\sitefinal\cacheObject.php:20 Stack trace: #0 C:\xampp\htdocs\sitefinal\cacheObject.php(20): serialize(Object(SimpleXMLElement)) 

任何帮助这个程序工作的人都会非常感谢。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2011-10-18 01:22:46

可能是像many built-in PHP objects, cannot be serialized这样的SimpleXMLElement类。

相反,您可以调用类方法asXML (如果不传递任何参数,它将返回一个有效的XML字符串)并将其序列化。然后,您可以通过对此字符串调用simplexml_load_string()来重新创建SimpleXMLElement类。

票数 3
EN

Stack Overflow用户

发布于 2015-10-22 15:02:54

Magpierss (免费开源)被认为可以缓存外部xml文件。我几年前就用过了。您为软件设置了再次提取xml文件的时间范围。它工作得很好。我看到的唯一问题是,它一直在拉取xml文件,无论是否有前端请求,这都会耗尽服务器。然而,我认为这可能会有一个解决方案。祝好运。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/7797093

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档