【问题标题】:php simplexml object cachingphp simplexml对象缓存
【发布时间】:2011-10-17 17:05:47
【问题描述】:

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

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));
  }   

函数调用如下:

$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);}

我收到以下错误:

    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)) 

非常感谢任何帮助使该程序正常工作。

【问题讨论】:

    标签: php xml caching rss


    【解决方案1】:

    可能是SimpleXMLElement 类,如many built-in PHP objects, cannot be serialized

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

    【讨论】:

    • 你能给出一些在这种情况下的过程的代码示例吗
    • 如果对象不能被序列化,你真的只能缓存提要的响应。我认为这会改变问题。
    【解决方案2】:

    Magpierss(免费开源)应该缓存外部 xml 文件。几年前我用过。您为软件设置了一个时间范围以再次提取 xml 文件。它运作良好。我看到的唯一问题是,无论是否有前端请求正在使用服务器,它都会不断拉取 xml 文件。我认为可能有一个解决办法。祝你好运。

    【讨论】:

      猜你喜欢
      • 2011-08-12
      • 2013-06-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-23
      • 2016-06-12
      相关资源
      最近更新 更多