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

simple xml cache example

{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}

 this cache is used in Yii Application but I just use the way that we use in normal php coding, to cache the xml content.