php利用PHPExcel类导出导入Excel用法

 更新时间:2016年11月25日 16:22  点击:1828
PHPExcel类是php一个excel表格处理插件了,下面我来给大家介绍利用PHPExcel类来导入与导出excel表格的应用方法,有需要了解的朋友不防参考参考(PHPExcel自己百度下载这里不介绍了)。

导出Excel用法

//设置环境变量(新增PHPExcel) 

 代码如下 复制代码

set_include_path('.'. PATH_SEPARATOR . Yii::app()->basePath.'/lib/PHPExcel' . PATH_SEPARATOR .

get_include_path()); 
//注:在yii中,也可以直接Yii::import(“application.lib.PHPExcel.*”); 
 
//引入PHPExcel相关文件 
require_once "PHPExcel.php"; 
require_once 'PHPExcel/IOFactory.php'; 
require_once 'PHPExcel/Writer/Excel5.php'; 

//把要导出的内容放到表格

 代码如下 复制代码

//新建 

$resultPHPExcel = new PHPExcel(); 
//设置参数 

//设值 

$resultPHPExcel->getActiveSheet()->setCellValue('A1', '季度'); 
$resultPHPExcel->getActiveSheet()->setCellValue('B1', '名称'); 
$resultPHPExcel->getActiveSheet()->setCellValue('C1', '数量'); 
$i = 2; 
foreach($data as $item){ 
$resultPHPExcel->getActiveSheet()->setCellValue('A' . $i, $item['quarter']); 
$resultPHPExcel->getActiveSheet()->setCellValue('B' . $i, $item['name']); 
$resultPHPExcel->getActiveSheet()->setCellValue('C' . $i, $item['number']); 
$i ++; 
}

设置导出参数

 代码如下 复制代码

//设置导出文件名 

$outputFileName = 'total.xls'; 

$xlsWriter = new PHPExcel_Writer_Excel5($resultPHPExcel); 

//ob_start(); ob_flush(); 

header("Content-Type: application/force-download"); 

header("Content-Type: application/octet-stream"); 

header("Content-Type: application/download"); 

header('Content-Disposition:inline;filename="'.$outputFileName.'"'); 

header("Content-Transfer-Encoding: binary"); 

header("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); 

header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); 

header("Cache-Control: must-revalidate, post-check=0, pre-check=0"); 

header("Pragma: no-cache"); 

$xlsWriter->save( "php://output" );

输出有错。 

默认$xlsWriter->save( "php://output" );可能因为缓存不够大,而显示不完整,所以做个中转,方式如下: 

 代码如下 复制代码

 

$finalFileName = (Yii::app()->basePath.'/runtime/'.time().'.xls'; 

$xlsWriter->save($finalFileName); 

echo file_get_contents($finalFileName); 

//file_get_contents() 函数把整个文件读入一个字符串中。和 file() 一样,不同的是 file_get_contents() 把文

件读入一个字符串。 


导入Excel用法

 代码如下 复制代码

<?
if($_POST['leadExcel'] == "true")
{
    $filename = $_FILES['inputExcel']['name'];
    $tmp_name = $_FILES['inputExcel']['tmp_name'];
    $msg = uploadFile($filename,$tmp_name);
    echo $msg;
}

//导入Excel文件
function uploadFile($file,$filetempname)
{
    //自己设置的上传文件存放路径
    $filePath = 'upFile/';
    $str = "";  
    //下面的路径按照你PHPExcel的路径来修改
    require_once '../PHPExcel/PHPExcel.php';
    require_once '../PHPExcel/PHPExcel/IOFactory.php';
    require_once '../PHPExcel/PHPExcel/Reader/Excel5.php';

    //注意设置时区
    $time=date("y-m-d-H-i-s");//去当前上传的时间
    //获取上传文件的扩展名
    $extend=strrchr ($file,'.');
    //上传后的文件名
    $name=$time.$extend;
    $uploadfile=$filePath.$name;//上传后的文件名地址
    //move_uploaded_file() 函数将上传的文件移动到新位置。若成功,则返回 true,否则返回 false。
    $result=move_uploaded_file($filetempname,$uploadfile);//假如上传到当前目录下
    //echo $result;
    if($result) //如果上传文件成功,就执行导入excel操作
    {
        include "conn.php";
        $objReader = PHPExcel_IOFactory::createReader('Excel5');//use excel2007 for 2007 format
        $objPHPExcel = $objReader->load($uploadfile);
        $sheet = $objPHPExcel->getSheet(0);
        $highestRow = $sheet->getHighestRow();           //取得总行数
        $highestColumn = $sheet->getHighestColumn(); //取得总列数
       
        /* 第一种方法

        //循环读取excel文件,读取一条,插入一条
        for($j=1;$j<=$highestRow;$j++)                        //从第一行开始读取数据
        {
            for($k='A';$k<=$highestColumn;$k++)            //从A列读取数据
            {
                //
                这种方法简单,但有不妥,以'\'合并为数组,再分割\为字段值插入到数据库
                实测在excel中,如果某单元格的值包含了\导入的数据会为空       
                //
                $str .=$objPHPExcel->getActiveSheet()->getCell("$k$j")->getValue().'\';//读取单元格
            }
            //echo $str; die();
            //explode:函数把字符串分割为数组。
            $strs = explode("\",$str);
            $sql = "INSERT INTO te(`1`, `2`, `3`, `4`, `5`) VALUES (
            '{$strs[0]}',
            '{$strs[1]}',
            '{$strs[2]}',
            '{$strs[3]}',
            '{$strs[4]}')";
            //die($sql);
            if(!mysql_query($sql))
            {
                return false;
                echo 'sql语句有误';
            }
            $str = "";
        } 
        unlink($uploadfile); //删除上传的excel文件
        $msg = "导入成功!";
        */

        /* 第二种方法*/
        $objWorksheet = $objPHPExcel->getActiveSheet();
        $highestRow = $objWorksheet->getHighestRow();
        echo 'highestRow='.$highestRow;
        echo "<br>";
        $highestColumn = $objWorksheet->getHighestColumn();
        $highestColumnIndex = PHPExcel_Cell::columnIndexFromString($highestColumn);//总列数
        echo 'highestColumnIndex='.$highestColumnIndex;
        echo "<br>";
        $headtitle=array();
        for ($row = 1;$row <= $highestRow;$row++)
        {
            $strs=array();
            //注意highestColumnIndex的列数索引从0开始
            for ($col = 0;$col < $highestColumnIndex;$col++)
            {
                $strs[$col] =$objWorksheet->getCellByColumnAndRow($col, $row)->getValue();
            }   
            $sql = "INSERT INTO te(`1`, `2`, `3`, `4`, `5`) VALUES (
            '{$strs[0]}',
            '{$strs[1]}',
            '{$strs[2]}',
            '{$strs[3]}',
            '{$strs[4]}')";
            //die($sql);
            if(!mysql_query($sql))
            {
                return false;
                echo 'sql语句有误';
            }
        }
    }
    else
    {
       $msg = "导入失败!";
    }
    return $msg;
}
?>

HTML网页代码

 代码如下 复制代码

<form action="upload.php" method="post" enctype="multipart/form-data">
    <input type="hidden" name="leadExcel" value="true">
    <table align="center" width="90%" border="0">
    <tr>
       <td>
        <input type="file" name="inputExcel"><input type="submit" value="导入数据">
       </td>
    </tr>
    </table>
</form>

本程序可以快速的实现把我们的文件利用php压缩类压缩成我们想的zip,或者rar 的压缩包,后缀名可以自定义哦, 压缩算法是来自国外一个网站抄的。

首先实例化,然后传参。两个参数。第一个关于你文件地址的一个Array。第二个是要你要保存的压缩包文件的绝对地址。

For example:

 代码如下 复制代码
        $zipfiles =array("/root/pooy/test1.txt","/root/pooy/test2.txt");
        $z = new PHPZip();
        //$randomstr = random(8);
        $zipfile = TEMP."/photocome_".$groupid.".zip";

        $z->Zip($zipfiles, $zipfile);

//添加文件列表PHP的ZIP压缩类如下:

 代码如下 复制代码

<?php
#
# PHPZip v1.2 by Sext (sext@neud.net) 2002-11-18
#     (Changed: 2003-03-01)
#
# Makes zip archive
#
# Based on "Zip file creation class", uses zLib
#
#

class PHPZip
{
    function Zip($dir, $zipfilename)
    {
        if (@function_exists('gzcompress'))
        {   
            $curdir = getcwd();
            if (is_array($dir))
            {
                    $filelist = $dir;
            }
            else
            {
                $filelist = $this -> GetFileList($dir);
            }

            if ((!empty($dir))&&(!is_array($dir))&&(file_exists($dir))) chdir($dir);
            else chdir($curdir);

            if (count($filelist)>0)
            {
                foreach($filelist as $filename)
                {
                    if (is_file($filename))
                    {
                        $fd = fopen ($filename, "r");
                        $content = fread ($fd, filesize ($filename));
                        fclose ($fd);

                        if (is_array($dir)) $filename = basename($filename);
                        $this -> addFile($content, $filename);
                    }
                }
                $out = $this -> file();

                chdir($curdir);
                $fp = fopen($zipfilename, "w");
                fwrite($fp, $out, strlen($out));
                fclose($fp);
            }
            return 1;
        }
        else return 0;
    }

    function GetFileList($dir)
    {
        if (file_exists($dir))
        {
            $args = func_get_args();
            $pref = $args[1];

            $dh = opendir($dir);
            while($files = readdir($dh))
            {
                if (($files!=".")&&($files!=".."))
                {
                    if (is_dir($dir.$files))
                    {
                        $curdir = getcwd();
                        chdir($dir.$files);
                        $file = array_merge($file, $this -> GetFileList("", "$pref$files/"));
                        chdir($curdir);
                    }
                    else $file[]=$pref.$files;
                }
            }
            closedir($dh);
        }
        return $file;
    }

    var $datasec      = array();
    var $ctrl_dir     = array();
    var $eof_ctrl_dir = "x50x4bx05x06x00x00x00x00";
    var $old_offset   = 0;

    /**
     * Converts an Unix timestamp to a four byte DOS date and time format (date
     * in high two bytes, time in low two bytes allowing magnitude comparison).
     *
     * @param  integer  the current Unix timestamp
     *
     * @return integer  the current date in a four byte DOS format
     *
     * @access private
     */
    function unix2DosTime($unixtime = 0) {
        $timearray = ($unixtime == 0) ? getdate() : getdate($unixtime);

        if ($timearray['year'] < 1980) {
            $timearray['year']    = 1980;
            $timearray['mon']     = 1;
            $timearray['mday']    = 1;
            $timearray['hours']   = 0;
            $timearray['minutes'] = 0;
            $timearray['seconds'] = 0;
        } // end if

        return (($timearray['year'] - 1980) << 25) | ($timearray['mon'] << 21) | ($timearray['mday'] << 16) |
                ($timearray['hours'] << 11) | ($timearray['minutes'] << 5) | ($timearray['seconds'] >> 1);
    } // end of the 'unix2DosTime()' method

    /**
     * Adds "file" to archive
     *
     * @param  string   file contents
     * @param  string   name of the file in the archive (may contains the path)
     * @param  integer  the current timestamp
     *
     * @access public
     */
    function addFile($data, $name, $time = 0)
    {
        $name     = str_replace('\', '/', $name);

        $dtime    = dechex($this->unix2DosTime($time));
        $hexdtime = 'x' . $dtime[6] . $dtime[7]
                  . 'x' . $dtime[4] . $dtime[5]
                  . 'x' . $dtime[2] . $dtime[3]
                  . 'x' . $dtime[0] . $dtime[1];
        eval('$hexdtime = "' . $hexdtime . '";');

        $fr   = "x50x4bx03x04";
        $fr   .= "x14x00";            // ver needed to extract
        $fr   .= "x00x00";            // gen purpose bit flag
        $fr   .= "x08x00";            // compression method
        $fr   .= $hexdtime;             // last mod time and date

        // "local file header" segment
        $unc_len = strlen($data);
        $crc     = crc32($data);
        $zdata   = gzcompress($data);
        $c_len   = strlen($zdata);
        $zdata   = substr(substr($zdata, 0, strlen($zdata) - 4), 2); // fix crc bug
        $fr      .= pack('V', $crc);             // crc32
        $fr      .= pack('V', $c_len);           // compressed filesize
        $fr      .= pack('V', $unc_len);         // uncompressed filesize
        $fr      .= pack('v', strlen($name));    // length of filename
        $fr      .= pack('v', 0);                // extra field length
        $fr      .= $name;

        // "file data" segment
        $fr .= $zdata;

        // "data descriptor" segment (optional but necessary if archive is not
        // served as file)
        $fr .= pack('V', $crc);                 // crc32
        $fr .= pack('V', $c_len);               // compressed filesize
        $fr .= pack('V', $unc_len);             // uncompressed filesize

        // add this entry to array
        $this -> datasec[] = $fr;
        $new_offset        = strlen(implode('', $this->datasec));

        // now add to central directory record
        $cdrec = "x50x4bx01x02";
        $cdrec .= "x00x00";                // version made by
        $cdrec .= "x14x00";                // version needed to extract
        $cdrec .= "x00x00";                // gen purpose bit flag
        $cdrec .= "x08x00";                // compression method
        $cdrec .= $hexdtime;                 // last mod time & date
        $cdrec .= pack('V', $crc);           // crc32
        $cdrec .= pack('V', $c_len);         // compressed filesize
        $cdrec .= pack('V', $unc_len);       // uncompressed filesize
        $cdrec .= pack('v', strlen($name) ); // length of filename
        $cdrec .= pack('v', 0 );             // extra field length
        $cdrec .= pack('v', 0 );             // file comment length
        $cdrec .= pack('v', 0 );             // disk number start
        $cdrec .= pack('v', 0 );             // internal file attributes
        $cdrec .= pack('V', 32 );            // external file attributes - 'archive' bit set

        $cdrec .= pack('V', $this -> old_offset ); // relative offset of local header
        $this -> old_offset = $new_offset;

        $cdrec .= $name;

        // optional extra field, file comment goes here
        // save to central directory
        $this -> ctrl_dir[] = $cdrec;
    } // end of the 'addFile()' method

    /**
     * Dumps out file
     *
     * @return  string  the zipped file
     *
     * @access public
     */
    function file()
    {
        $data    = implode('', $this -> datasec);
        $ctrldir = implode('', $this -> ctrl_dir);

        return
            $data .
            $ctrldir .
            $this -> eof_ctrl_dir .
            pack('v', sizeof($this -> ctrl_dir)) .  // total # of entries "on this disk"
            pack('v', sizeof($this -> ctrl_dir)) .  // total # of entries overall
            pack('V', strlen($ctrldir)) .           // size of central dir
            pack('V', strlen($data)) .              // offset to start of central dir
            "x00x00";                             // .zip file comment length
    } // end of the 'file()' method

} // end of the 'PHPZip' class
?>

php本身是不具备可以带有实时上传进度条功能了,如果想有这种功能我们一般会使用ajax来实现,但是php提供了一个apc,他就可以与php配置实现上传进度条哦。

主要针对的是window上的应用。
1.服务器要支持apc扩展,没有此扩展的话,百度一下php_apc.dll ,下载一个扩展扩展要求php.5.2以上。
2.配置apc相关配置,重启apache

 代码如下 复制代码
extension=php_apc.dll  
apc.rfc1867 = on  
apc.max_file_size = 1000M  
upload_max_filesize = 1000M  
post_max_size = 1000M  

 

说明一下:至于参数要配多大,得看项目需要apc.max_file_size,  设置apc所支持上传文件的大小,要求apc.max_file_size <=upload_max_filesize  并且apc.max_file_size <=post_max_size.重新启动apache即可实现apc的支持.
3.在代码里面利用phpinfo();查看apc扩展安装了没有。
4.下面是实现代码:
getprogress.php

 代码如下 复制代码

<?php  
session_start();  
if(isset($_GET['progress_key'])) {  
  $status = apc_fetch('upload_'.$_GET['progress_key']);  
  echo ($status['current']/$status['total'])*100;  
}  
?>  
upload.php

PHP Code
<?php  
   $id = $_GET['id'];  
?>  
<form enctype="multipart/form-data" id="upload_form" action="target.php" method="POST">  
<input type="hidden" name="APC_UPLOAD_PROGRESS"   
       id="progress_key"  value="<?php echo $id?>"/>  
<input type="file" id="test_file" name="test_file"/><br/>  
<input onclick="window.parent.startProgress(); return true;"  
 type="submit" value="上传"/>  
</form>  

target.php

 代码如下 复制代码
<?php    
set_time_limit(600);  
if($_SERVER['REQUEST_METHOD']=='POST') {  
  move_uploaded_file($_FILES["test_file"]["tmp_name"],   
  dirname($_SERVER['SCRIPT_FILENAME'])."/UploadTemp/" . $_FILES["test_file"]["name"]);//UploadTemp文件夹位于此脚本相同目录下  
  echo "<p>上传成功</p>";  
}  
?>  

index.php

 代码如下 复制代码

<?php  
   $id = md5(uniqid(rand(), true));  
?>  
<html>  
<head><title>上传进度</title></head>  
<body>  
<script src="js/jquery-1.4.4.min.js" language="javascript"></script>  
  
  
<script language="javascript">  
var proNum=0;  
var loop=0;  
var progressResult;  
function sendURL() {  
            $.ajax({  
                        type : 'GET',  
                        url : "getprogress.php?progress_key=<?php echo $id;?>",  
                        async : true,  
                        cache : false,  
                        dataType : 'json',  
                        data: "progress_key=<?php echo $id;?>",  
                        success : function(e) {  
                                     progressResult = e;  
                                      proNum=parseInt(progressResult);  
                                      document.getElementById("progressinner").style.width = proNum+"%";  
                                      document.getElementById("showNum").innerHTML = proNum+"%";  
                                      if ( proNum < 100){  
                                        setTimeout("getProgress()", 100);  
                                      }   
                                   
                        }  
            });  
    
}  
  
function getProgress(){  
 loop++;  
  
 sendURL();  
}  
var interval;  
function startProgress(){  
    document.getElementById("progressouter").style.display="block";  
   setTimeout("getProgress()", 100);  
}  
</script>  
<iframe id="theframe" name="theframe"   
        src="upload.php?id=<?php echo $id; ?>"   
        style="border: none; height: 100px; width: 400px;" >   
</iframe>  
<br/><br/>  
<div id="progressouter" style="width: 500px; height: 20px; border: 6px solid red; display:none;">  
   <div id="progressinner" style="position: relative; height: 20px; background-color: purple; width: 0%; "></div>  
</div>  
<div id='showNum'></div><br>  
<div id='showNum2'></div>  
</body>  
</html>  

小偷程序其实就是利用了php中的一特定函数实现采集别人网站的内容,然后通过正则分析把我们想要的内容保存到自己本地数据库了,下面我来介绍php小偷程序的实现方法,有需要的朋友可参考。

在下面采集数据过程中file_get_contents函数是关键了,下面我们来看看file_get_contents函数语法

string file_get_contents ( string $filename [, bool $use_include_path = false [, resource $context [, int $offset = -1 [, int $maxlen ]]]] )
和 file() 一样,只除了 file_get_contents() 把文件读入一个字符串。将在参数 offset 所指定的位置开始读取长度为 maxlen 的内容。如果失败, file_get_contents() 将返回 FALSE。

file_get_contents() 函数是用来将文件的内容读入到一个字符串中的首选方法。如果操作系统支持还会使用内存映射技术来增强性能。

 代码如下 复制代码

<?php
$homepage = file_get_contents('http://www.111cn.net/');
echo $homepage;
?>

这样$homepage就是我们采集网的内容给保存下来了,好了说了这么多我们开始吧。

 代码如下 复制代码

<?php

function fetch_urlpage_contents($url){
$c=file_get_contents($url);
return $c;
}
//获取匹配内容
function fetch_match_contents($begin,$end,$c)
{
$begin=change_match_string($begin);
$end=change_match_string($end);
$p = "{$begin}(.*){$end}";
if(eregi($p,$c,$rs))
{
return $rs[1];}
else { return "";}
}//转义正则表达式字符串
function change_match_string($str){
//注意,以下只是简单转义
//$old=array("/","$");
//$new=array("/","$");
$str=str_replace($old,$new,$str);
return $str;
}

//采集网页
function pick($url,$ft,$th)
{
$c=fetch_urlpage_contents($url);
foreach($ft as $key => $value)
{
$rs[$key]=fetch_match_contents($value["begin"],$value["end"],$c);
if(is_array($th[$key]))
{ foreach($th[$key] as $old => $new)
{
$rs[$key]=str_replace($old,$new,$rs[$key]);
}
}
}
return $rs;
}

$url="http://www.111cn.net"; //要采集的地址
$ft["title"]["begin"]="<title>"; //截取的开始点
$ft["title"]["end"]="</title>"; //截取的结束点
$th["title"]["中山"]="广东"; //截取部分的替换

$ft["body"]["begin"]="<body>"; //截取的开始点
$ft["body"]["end"]="</body>"; //截取的结束点
$th["body"]["中山"]="广东"; //截取部分的替换

$rs=pick($url,$ft,$th); //开始采集

echo $rs["title"];
echo $rs["body"]; //输出
?>

以下代码从上一面修改而来,专门用于提取网页所有超链接,邮箱或其他特定内容

 代码如下 复制代码

<?php

function fetch_urlpage_contents($url){
$c=file_get_contents($url);
return $c;
}
//获取匹配内容
function fetch_match_contents($begin,$end,$c)
{
$begin=change_match_string($begin);
$end=change_match_string($end);
$p = "#{$begin}(.*){$end}#iU";//i表示忽略大小写,U禁止贪婪匹配
if(preg_match_all($p,$c,$rs))
{
return $rs;}
else { return "";}
}//转义正则表达式字符串
function change_match_string($str){
//注意,以下只是简单转义
$old=array("/","$",'?');
$new=array("/","$",'?');
$str=str_replace($old,$new,$str);
return $str;
}

//采集网页
function pick($url,$ft,$th)
{
$c=fetch_urlpage_contents($url);
foreach($ft as $key => $value)
{
$rs[$key]=fetch_match_contents($value["begin"],$value["end"],$c);
if(is_array($th[$key]))
{ foreach($th[$key] as $old => $new)
{
$rs[$key]=str_replace($old,$new,$rs[$key]);
}
}
}
return $rs;
}

$url="http://www.111cn.net"; //要采集的地址
$ft["a"]["begin"]='<a'; //截取的开始点<br />
$ft["a"]["end"]='>'; //截取的结束点

$rs=pick($url,$ft,$th); //开始采集

print_r($rs["a"]);

?>

小提示file_get_contents很是容易被防采集了,我们可以使用curl来模仿用户对网站进行访问,这算比上面要高级不少哦,file_get_contents()效率稍低些,常用失败的情况、curl()效率挺高的,支持多线程,不过需要开启下curl扩展。下面是curl扩展开启的步骤:

1、将PHP文件夹下的三个文件php_curl.dll,libeay32.dll,ssleay32.dll复制到system32下;

2、将php.ini(c:WINDOWS目录下)中的;extension=php_curl.dll中的分号去掉;

3、重启apache或者IIS。

简单的抓取页面函数,附带伪造 Referer 和 User_Agent 功能

 代码如下 复制代码

<?php
function GetSources($Url,$User_Agent='',$Referer_Url='') //抓取某个指定的页面
{
//$Url 需要抓取的页面地址
//$User_Agent 需要返回的user_agent信息 如“baiduspider”或“googlebot”
$ch = curl_init();
curl_setopt ($ch, CURLOPT_URL, $Url);
curl_setopt ($ch, CURLOPT_USERAGENT, $User_Agent);
curl_setopt ($ch, CURLOPT_REFERER, $Referer_Url);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION,1);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
$MySources = curl_exec ($ch);
curl_close($ch);
return $MySources;
}
$Url = "http://www.111cn.net"; //要获取内容的也没
$User_Agent = "baiduspider+(+http://www.baidu.com/search/spider.htm)";
$Referer_Url = 'http://www.111cn.net/';
echo GetSources($Url,$User_Agent,$Referer_Url);
?>

本人给大家推一个不错php文件缓存类文件,从各方面来看本缓存类很合理并且适用于大型网站使用哦,有需要的朋友可参考参考。
 代码如下 复制代码

<?php
class Cache {
 /** 缓存目录 **/
 var $CacheDir        = './c';
 /** 缓存的文件 **/
 var $CacheFile        = '';
 /** 文件缓存时间(分钟) **/
 var $CacheTime        = 0;
 /** 文件是否已缓存 **/
 var $CacheFound        = False;
 /** 错误及调试信息 **/
 var $DebugMsg        = NULL;

 function Cache($CacheTime = 0) {
  $this->CacheTime    = $CacheTime;
 }

 private function Run() {
  /** 缓存时间大于0,检测缓存文件的修改时间,在缓存时间内为缓存文件名,超过缓存时间为False,
                小于等于0,返回false,并清理已缓存的文件
         **/
  Return $this->CacheTime ? $this->CheckCacheFile() : $this->CleanCacheFile();
 }
 function GetCache($VistUrl,$CacheFileType = 'html')
 {
  $this->SetCacheFile($VistUrl,$CacheFileType);

  $fileName=$this->CheckCacheFile();
  if($fileName)
  {
   $fp = fopen($fileName,"r");
   $content_= fread($fp, filesize($fileName));
   fclose($fp);
   return $content_;
  }
  else
  {
   return false;
  }
 }
 private function SetCacheFile($VistUrl,$CacheFileType = 'html') {
  if(empty($VistUrl)) {
   /** 默认为index.html **/
   $this->CacheFile = 'index';
  }else {
   /** 传递参数为$_POST时 **/
   $this->CacheFile = is_array($VistUrl) ? implode('.',$VistUrl) : $VistUrl;
  }
  $this->CacheFile = $this->CacheDir.'/'.md5($this->CacheFile);
  $this->CacheFile.= '.'.$CacheFileType;
 }

 function SetCacheTime($t = 60) {
  $this->CacheTime = $t;
 }

 private function CheckCacheFile() {
  if(!$this->CacheTime || !file_exists($this->CacheFile)) {Return False;}
  /** 比较文件的建立/修改日期和当前日期的时间差 **/
  $GetTime=(Time()-Filemtime($this->CacheFile))/(60*1);
  /** Filemtime函数有缓存,注意清理 **/
  Clearstatcache();
  $this->Debug('Time Limit '.($GetTime*60).'/'.($this->CacheTime*60).'');
  $this->CacheFound = $GetTime <= $this->CacheTime ? $this->CacheFile : False;
  Return $this->CacheFound;
 }

 function SaveToCacheFile($VistUrl,$Content,$CacheFileType = 'html') {
  $this->SetCacheFile($VistUrl,$CacheFileType);
  if(!$this->CacheTime) {
   Return False;
  }
  /** 检测缓存目录是否存在 **/
  if(true === $this->CheckCacheDir()) {
   $CacheFile = $this->CacheFile;
   $CacheFile = str_replace('//','/',$CacheFile);
   $fp = @fopen($CacheFile,"wb");
   if(!$fp) {
    $this->Debug('Open File '.$CacheFile.' Fail');
   }else {
    if(@!fwrite($fp,$Content)){
     $this->Debug('Write '.$CacheFile.' Fail');
    }else {
     $this->Debug('Cached File');
    };
    @fclose($fp);
   }
  }else {
   /** 缓存目录不存在,或不能建立目录 **/
   $this->Debug('Cache Folder '.$this->CacheDir.' Not Found');
  }
 }

 private function CheckCacheDir() {
  if(file_exists($this->CacheDir)) { Return true; }
  /** 保存当前工作目录 **/
  $Location = getcwd();
  /** 把路径划分成单个目录 **/
  $Dir = split("/", $this->CacheDir);
  /** 循环建立目录 **/
  $CatchErr = True;
  for ($i=0; $i<count($Dir); $i++){
   if (!file_exists($Dir[$i])){
    /** 建立目录失败会返回False 返回建立最后一个目录的返回值 **/
    $CatchErr = @mkdir($Dir[$i],0777);
   }
   @chdir($Dir[$i]);
  }
  /** 建立完成后要切换到原目录 **/
  chdir($Location);
  if(!$CatchErr) {
   $this->Debug('Create Folder '.$this->CacheDir.' Fail');
  }
  Return $CatchErr;
 }

 private function CleanCacheFile() {
  if(file_exists($this->CacheFile)) {
   @chmod($this->CacheFile,777);
   @unlink($this->CacheFile);
  }
  /** 置没有缓存文件 **/
  $this->CacheFound = False;
  Return $this->CacheFound;
 }

 function Debug($msg='') {
  if(DEBUG) {
   $this->DebugMsg[] = '[Cache]'.$msg;
  }
 }

 function GetError() {
  Return empty($this->DebugMsg) ? '' : "<br>n".implode("<br>n",$this->DebugMsg);
 }
}/* end of class */


?>

[!--infotagslink--]

相关文章

  • C#中using的三种用法

    using 指令有两个用途: 允许在命名空间中使用类型,以便您不必限定在该命名空间中使用的类型。 为命名空间创建别名。 using 关键字还用来创建 using 语句 定义一个范围,将在此...2020-06-25
  • 详解在IDEA中将Echarts引入web两种方式(使用js文件和maven的依赖导入)

    这篇文章主要介绍了在IDEA中将Echarts引入web两种方式(使用js文件和maven的依赖导入),本文通过图文并茂的形式给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下...2020-07-11
  • iscroll.js 用法介绍

    最新版下载: http://www.csdn123.com/uploadfile/2015/0428/20150428062734485.zip 概要 iScroll 4 这个版本完全重写了iScroll这个框架的原始代码。这个项目的产生...2016-05-19
  • C#中的try catch finally用法分析

    这篇文章主要介绍了C#中的try catch finally用法,以实例形式分析了try catch finally针对错误处理时的不同用法,具有一定的参考借鉴价值,需要的朋友可以参考下...2020-06-25
  • C++中cin的用法详细

    这篇文章主要介绍了C++中cin的用法详细,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2020-04-25
  • R语言导入导出数据的几种方法汇总

    这篇文章主要给大家总结介绍了R语言导入导出数据的几种方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2021-05-06
  • 示例详解react中useState的用法

    useState 通过在函数组件里调用它来给组件添加一些内部 state,React 会在重复渲染时保留这个 state,接下来通过一个示例来看看怎么使用 useState吧...2021-06-04
  • Delphi常用关键字用法详解

    这篇文章主要介绍了Delphi常用关键字用法,包括了各个常用的关键字及其详细用法,需要的朋友可以参考下...2020-06-30
  • PHP中print_r、var_export、var_dump用法介绍

    文章详细的介绍了关于PHP中print_r、var_export、var_dump区别比较以及这几个在php不同的应用中的用法,有需要的朋友可以参考一下 可以看出print_r跟var_export都...2016-11-25
  • php中php://input的用法详细

    在使用xml-rpc的时候,server端获取client数据,主要是通过php输入流input,而不是$_POST数组。所以,这里主要探讨php输入流php://input。 下面的例子摘取的是wordpres...2016-11-25
  • MySQL中的主键以及设置其自增的用法教程

    1、声明主键的方法: 您可以在创建表的时候就为表加上主键,如: CREATE TABLE tbl_name ([字段描述省略...], PRIMARY KEY(index_col_name)); 也可以更新表结构时为表加上主键,如: ALTER TABLE tbl_name ADD PRIMARY KEY (in...2015-11-24
  • C#中this的用法集锦

    本文给大家汇总介绍了C#中的几种this用法,相信大家应该有用过,但你用过几种?以下是个人总结的this几种用法,欢迎大家拍砖,废话少说,直接列出用法及相关代码。...2020-06-25
  • window.onerror()的用法与实例分析

    目前在做window.onerror时上报js错误信息的事,整理下相关资料,需要的朋友可以参考下...2016-01-29
  • C语言循环结构与时间函数用法实例教程

    这篇文章主要介绍了C语言循环结构与时间函数用法,是C语言中非常重要的一个技巧,需要的朋友可以参考下...2020-04-25
  • phpexcel导入xlsx文件报错xlsx is not recognised as an OLE file 怎么办

    phpexcel是一款php读写excel的插件了,小编有一个这样的功能要来实现,但是在导入xlsx时发现xlsx is not recognised as an OLE file 了,但是导入xls是没有问题了,碰到这种...2016-11-25
  • C#数据导入到EXCEL的方法

    今天小编就为大家分享一篇关于C#数据导入到EXCEL的方法,小编觉得内容挺不错的,现在分享给大家,具有很好的参考价值,需要的朋友一起跟随小编来看看吧...2020-06-25
  • php中 ->与 ==>符号的用法与区别

    本文章来给大家介绍一下在php中 ->与 ==>符号的用法与区别,有需要了解的朋友可尝试参考。 “->”(减号、右尖括号) 用于类中,访问类里的函数或对象,比如:...2016-11-25
  • 让C# Excel导入导出 支持不同版本Office

    让C# Excel导入导出,支持不同版本的Office,感兴趣的小伙伴们可以参考一下...2020-06-25
  • foreach()有两种用法

    foreach()有两种用法 1: foreach(array as $value) { 表达式; } 这里的array是你要遍历的数组名,每次循环中,array数组的当前元素的值被赋给$value,...2016-11-25
  • ES6学习教程之Promise用法详解

    这篇文章主要给大家介绍了关于ES6学习教程之Promise用法的相关资料,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2020-11-23