2011-04-03 17:26:20 0 评论 PHP Boy.Lee

Simple Xml 缓存示例

{code}

    //xml read and cache
    $filePath = Yii::app()->basePath.'/../DBox/new.xml';
    $urlXml = 'http://yiilib.com/rss/';
    $strXml = '';

    if (file_exists($filePath)){
    //check time to read or rebuild
    $timeUpdate = filemtime($filePath);
    if (time()-$timeUpdate>60*30){//time check
        //rebuild
        $content = file_get_contents($urlXml);
        $this->writeFile($filePath, $content);
        $strXml = $content;
    }else {
        //read
        $strXml = file_get_contents($filePath);
    }

    }else{
    //build first time
        $content = file_get_contents($urlXml);
        $this->writeFile($filePath, $content);
        $strXml = $content;
    }

    if ($strXml != ''){
        $xmlNews = simplexml_load_string($strXml);
    }else{
        $xmlNews = simplexml_load_file($urlXml);
    }

{writeFile function here}

 

{Boy Say}

应用在Yii应用程序中的一个简单缓存实例,使用了日常php缓存的方法,只要是减少xml网络加载的次数,每30分钟缓存一次。