PHP中利用PHPExcel导出Excel示例

 更新时间:2016年11月25日 16:20  点击:2097
在php中导出excel有一种最简单的方法就是导出csv文件,但要做到真正的导出excel文件我们可以借助于PHPExcel插件来实现。

PHPExcel是个很强大的PHP操作Excel的类库,但是对于简单的将数据用PHP 导出 Excel来说这有点显得复杂,在google code上有一个PHP 导出 Excel的类,可以简单调用,很方便。

 代码如下 复制代码

<?php
// load library
require 'php-excel.class.php';
// create a simple 2-dimensional array
$data = array(
        1 => array ('Name', 'Surname'),
        array('Schwarz', 'Oliver'),
        array('Test', 'Peter')
        );
// generate file (constructor parameters are optional)
$xls = new Excel_XML('UTF-8', false, 'My Test Sheet');
$xls->addArray($data);
$xls->generateXML('my-test');
?>

例2

 代码如下 复制代码

<?php
/**
 * PHPEXCEL生成excel文件
 * @author:firmy
 * @desc 支持任意行列数据生成excel文件,暂未添加单元格样式和对齐
 */

require_once 'library/PHPExcel.php';
require_once 'library/PHPExcel/Reader/Excel2007.php';
require_once 'library/PHPExcel/Reader/Excel5.php';
include_once 'library/PHPExcel/IOFactory.php';

$fileName = "test_excel";
$headArr = array("第一列","第二列","第三列");
$data = array(array(1,2),array(1,3),array(5,7));
getExcel($fileName,$headArr,$data);


function getExcel($fileName,$headArr,$data){
    if(empty($data) || !is_array($data)){
        die("data must be a array");
    }
    if(empty($fileName)){
        exit;
    }
    $date = date("Y_m_d",time());
    $fileName .= "_{$date}.xlsx";

    //创建新的PHPExcel对象
    $objPHPExcel = new PHPExcel();
    $objProps = $objPHPExcel->getProperties();
 
    //设置表头
    $key = ord("A");
    foreach($headArr as $v){
        $colum = chr($key);
        $objPHPExcel->setActiveSheetIndex(0) ->setCellValue($colum.'1', $v);
        $key += 1;
    }
   
    $column = 2;
    $objActSheet = $objPHPExcel->getActiveSheet();
    foreach($data as $key => $rows){ //行写入
        $span = ord("A");
        foreach($rows as $keyName=>$value){// 列写入
            $j = chr($span);
            $objActSheet->setCellValue($j.$column, $value);
            $span++;
        }
        $column++;
    }

    $fileName = iconv("utf-8", "gb2312", $fileName);
    //重命名表
    $objPHPExcel->getActiveSheet()->setTitle('Simple');
    //设置活动单指数到第一个表,所以Excel打开这是第一个表
    $objPHPExcel->setActiveSheetIndex(0);
    //将输出重定向到一个客户端web浏览器(Excel2007)
          header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
          header("Content-Disposition: attachment; filename="$fileName"");
          header('Cache-Control: max-age=0');
          $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
          if(!empty($_GET['excel'])){
            $objWriter->save('php://output'); //文件通过浏览器下载
        }else{
          $objWriter->save($fileName); //脚本方式运行,保存在当前目录
        }
  exit;

}

phpexcel类的下载地址:http://php-excel.googlecode.com/files/php-excel-v1.1-20090910.zip

在php中如果不仔细的去分析性能会发现file_get_contents与curl两个同很多共同点的,他们都可以采集文件打开文件,但是如果仔细一对比会发现很多不同点,下面我们一起来看看file_get_contents与curl区别。

PHP中fopen,file_get_contents,curl函数的区别:

1.fopen /file_get_contents 每次请求都会重新做DNS查询,并不对 DNS信息进行缓存。但是CURL会自动对DNS信息进行缓存。对同一域名下的网页或者图片的请求只需要一次DNS查询。这大大减少了DNS查询的次数。所以CURL的性能比fopen /file_get_contents 好很多。

2.fopen /file_get_contents 在请求HTTP时,使用的是http_fopen_wrapper,不会keeplive。而curl却可以。这样在多次请求多个链接时,curl效率会好一些。


3.fopen / file_get_contents 函数会受到php.ini文件中allow_url_open选项配置的影响。如果该配置关闭了,则该函数也就失效了。而curl不受该配置的影响。


4.curl 可以模拟多种请求,例如:POST数据,表单提交等,用户可以按照自己的需求来定制请求。而fopen / file_get_contents只能使用get方式获取数据。

file_get_contents 获取远程文件时会把结果都存在一个字符串中 fiels函数则会储存成数组形式
因此,我还是比较倾向于使用curl来访问远程url。Php有curl模块扩展,功能很是强大。

说了半天大家可能说性能怎么没对比呢,那我们就来看看


最近需要获取别人网站上的音乐数据。用了file_get_contents函数,但是总是会遇到获取失败的问题,尽管按照手册中的 例子设置了超时,可多数时候不会奏效:

 

 代码如下 复制代码
$config['context'] = stream_context_create(array(‘http’ => array(‘method’ => “GET”,
   ’timeout’ => 5//这个超时时间不稳定,经常不奏效
   )
  ));

这时候,看一下服务器的连接池,会发现一堆类似的错误,让我头疼万分:

 代码如下 复制代码
file_get_contents(http://***): failed to open stream…

现在改用了curl库,写了一个函数替换:

 代码如下 复制代码
function curl_file_get_contents($durl){
  $ch = curl_init();
  curl_setopt($ch, CURLOPT_URL, $durl);
  curl_setopt($ch, CURLOPT_TIMEOUT, 5);
  curl_setopt($ch, CURLOPT_USERAGENT, _USERAGENT_);
  curl_setopt($ch, CURLOPT_REFERER,_REFERER_);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  $r = curl_exec($ch);
  curl_close($ch);
   return $r;
}

如此,除了真正的网络问题外,没再出现任何问题。
这是别人做过的关于curl和file_get_contents的测试:
file_get_contents抓取google.com需用秒数:

 

2.31319094

2.30374217
2.21512604
3.30553889
2.30124092

curl使用的时间:

 

0.68719101

0.64675593
0.64326
0.81983113
0.63956594

差距很大?呵呵,从我使用的经验来说,这两个工具不只是速度有差异,稳定性也相差很大。

建议对网络数据抓取稳定性要求比较高的朋友使用上面的 curl_file_get_contents函数,不但稳定速度快,还能假冒浏览器欺骗目标地址哦


再看一个实例

后续贴出了curl和file_get_contents的对比结果,这边除了curl与file_get_contents的性能对比,还包含了他们的性能对比,讲之前看下如下的结果图:

curl与file_get_contents性能对比PHP源代码如下:

 代码如下 复制代码

<?php
/**
 
* 通过淘宝IP接口获取IP地理位置
 
* @param string $ip
 
* @return: string
 
**/
function getCityCurl($ip)
{
    $url="http://ip.taobao.com/service/getIpInfo.php?ip=".$ip;
    $ch = curl_init();
    $timeout = 5;
    curl_setopt ($ch, CURLOPT_URL, $url);
    curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
    $file_contents = curl_exec($ch);
    curl_close($ch);
 
    $ipinfo=json_decode($file_contents);
    if($ipinfo->code=='1'){
        return false;
    }
    $city = $ipinfo->data->region.$ipinfo->data->city;
    return $city;
}
 
function getCity($ip)
{
    $url="http://ip.taobao.com/service/getIpInfo.php?ip=".$ip;
    $ipinfo=json_decode(file_get_contents($url));
    if($ipinfo->code=='1'){
        return false;
    }
    $city = $ipinfo->data->region.$ipinfo->data->city;
    return $city;
}
 
// for file_get_contents
$startTime=explode(' ',microtime());
$startTime=$startTime[0] + $startTime[1];
for($i=1;$i<=10;$i++)
{
   echo getCity("121.207.247.202")."</br>";
}
$endTime = explode(' ',microtime());
$endTime = $endTime[0] + $endTime[1];
$totalTime = $endTime - $startTime;
echo 'file_get_contents:'.number_format($totalTime, 10, '.', "")." seconds</br>";
 
//for curl
$startTime2=explode(' ',microtime());
$startTime2=$startTime2[0] + $startTime2[1];
for($i=1;$i<=10;$i++)
{
   echo getCityCurl('121.207.247.202')."</br>";
}
$endTime2 = explode(' ',microtime());
$endTime2=$endTime2[0] + $endTime2[1];
$totalTime2 = $endTime2 - $startTime2;
echo "curl:".number_format($totalTime2, 10, '.', "")." seconds";
?>

测试访问

http://www.111cn.net

file_get_contents速度:4.2404510975 seconds
curl速度:2.8205530643 seconds

curl比file_get_contents速度快了30%左右,最重要的是服务器负载更低.

总结

file_get_contents处理频繁小的时候,用它感觉挺好的。没什么异常。如果你的文件被1k+人处理。那么你的服务器cpu就等着高升吧。所以建议自己和大家在以后写php代码的时候使用curl库。

 

php5.3或以上版本可以使用php管理crontab计划任务,下面我先来体验一下,有需要学习了解的朋友可进入参考。

1.使用php-crontab-manager管理计划任务
要求 PHP>=5.3

使用方法举例

 代码如下 复制代码

use phpmanagercrontabCrontabManager;

$crontab = new CrontabManager();
$crontab->enableOrUpdate('/tmp/my/crontab.txt');
$crontab->save();

添加一个简单的计划任务:

 代码如下 复制代码

use phpmanagercrontabCrontabManager;

$crontab = new Ssh2_crontab_manager();
$job = $crontab->newJob();
$job->on('* * * * *');
$job->onMinute('20-30')->doJob("echo foo");
$crontab->add($job);
$job->onMinute('35-40')->doJob("echo bar");
$crontab->add($job);
$crontab->save();


类文件

 代码如下 复制代码

<?php

Class Ssh2_crontab_manager {

 private $connection;
 private $path;
 private $handle;
 private $cron_file;

 function __construct($host=NULL, $port=NULL, $username=NULL, $password=NULL)
 {  
  $path_length  = strrpos(__FILE__, "/");
  $this->path   = substr(__FILE__, 0, $path_length) . '/';  
  $this->handle  = 'crontab.txt';
  $this->cron_file = "{$this->path}{$this->handle}";
  
  try
  {
   if (is_null($host) || is_null($port) || is_null($username) || is_null($password)) throw new Exception("The host, port, username and password arguments must be specified!");
  
   $this->connection = @ssh2_connect($host, $port);   
   if ( ! $this->connection) throw new Exception("The SSH2 connection could not be established.");

   $authentication = @ssh2_auth_password($this->connection, $username, $password);
   if ( ! $authentication) throw new Exception("Could not authenticate '{$username}' using pasword: '{$password}'.");
  }
  catch (Exception $e)
  {
   $this->error_message($e->getMessage());
  }
 }

 public function exec()
 {
  $argument_count = func_num_args();

  try
  {
   if ( ! $argument_count) throw new Exception("There is nothing to exececute, no arguments specified.");

   $arguments = func_get_args();
   
   $command_string = ($argument_count > 1) ? implode(" && ", $arguments) : $arguments[0];
   
   $stream = @ssh2_exec($this->connection, $command_string);
   if ( ! $stream) throw new Exception("Unable to execute the specified commands: <br />{$command_string}");
  }
  catch (Exception $e)
  {
   $this->error_message($e->getMessage());
  }

  return $this;
 }

 public function write_to_file($path=NULL, $handle=NULL)
 {
  if ( ! $this->crontab_file_exists())
  {  
   $this->handle = (is_null($handle)) ? $this->handle : $handle;
   $this->path   = (is_null($path))   ? $this->path   : $path;   
   $this->cron_file = "{$this->path}{$this->handle}";
   
   $init_cron = "crontab -l > {$this->cron_file} && [ -f {$this->cron_file} ] || > {$this->cron_file}";
   
   $this->exec($init_cron);  
  }
 
  return $this; 
 }
 
 public function remove_file()
 {  
  if ($this->crontab_file_exists()) $this->exec("rm {$this->cron_file}");  
  return $this;
 }
 
 public function append_cronjob($cron_jobs=NULL)
 {
  if (is_null($cron_jobs)) $this->error_message("Nothing to append!  Please specify a cron job or an array of cron jobs.");
  
  $append_cronfile = "echo '";  
  
  $append_cronfile .= (is_array($cron_jobs)) ? implode("n", $cron_jobs) : $cron_jobs;
  
  $append_cronfile .= "'  >> {$this->cron_file}";
  
  $install_cron = "crontab {$this->cron_file}";

  $this->write_to_file()->exec($append_cronfile, $install_cron)->remove_file();
  
  return $this;  
 }
 
 public function remove_cronjob($cron_jobs=NULL)
 { 
  if (is_null($cron_jobs)) $this->error_message("Nothing to remove!  Please specify a cron job or an array of cron jobs.");
  
  $this->write_to_file();
 
  $cron_array = file($this->cron_file, FILE_IGNORE_NEW_LINES);
  
  if (empty($cron_array))
  {
   $this->remove_file()->error_message("Nothing to remove!  The cronTab is already empty.");   
  }
  
  $original_count = count($cron_array);
  
  if (is_array($cron_jobs))
  {
   foreach ($cron_jobs as $cron_regex) $cron_array = preg_grep($cron_regex, $cron_array, PREG_GREP_INVERT);
  }
  else
  {
   $cron_array = preg_grep($cron_jobs, $cron_array, PREG_GREP_INVERT);
  }
  
  return ($original_count === count($cron_array)) ? $this->remove_file() : $this->remove_crontab()->append_cronjob($cron_array);
 }

 public function remove_crontab()
 {
  $this->remove_file()->exec("crontab -r");  
  return $this;
 }

 private function crontab_file_exists()
 {
  return file_exists($this->cron_file);
 }
 
 private function error_message($error)
 {
  die("<pre style='color:#EE2711'>ERROR: {$error}</pre>");
 }
 
}

项目地址
https://github.com/MediovskiTechnology/php-crontab-manager

2.Ssh2_crontab_manager 关于php管理计划任务的详细教程

具体内容参考:
http://net.tutsplus.com/tutorials/php/managing-cron-jobs-with-php-2/

参考资料:

http://stackoverflow.com/questions/4421020/use-php-to-create-edit-and-delete-crontab-jobs

 

缓存类是我们开发应用中会常用使用到的功能,下面我来给大家整理几个php文件缓存类了,各个文件缓存类写法不同,但在性能上会有区别,有兴趣测试的朋友可测试一下这些缓存类吧。

例1

 代码如下 复制代码

<?php
$fzz = new fzz_cache;
$fzz->kk = $_SERVER; //写入缓存
//$fzz->set("kk",$_SERVER,10000); //此方法不与类属性想冲突,可以用任意缓存名;
print_r($fzz->kk);  //读取缓存
//print_r($fzz->get("kk"));
//unset($fzz->kk); //删除缓存
//$fzz->_unset("kk");
var_dump(isset($fzz->kk)); //判断缓存是否存在
//$fzz->_isset("kk");
//$fzz->clear(); //清理过期缓存
//$fzz->clear_all(); //清理所有缓存文件
class fzz_cache{
 public $limit_time = 20000; //缓存过期时间
 public $cache_dir = "data"; //缓存文件保存目录

 //写入缓存
 function __set($key , $val){
  $this->_set($key ,$val);
 }
 //第三个参数为过期时间
 function _set($key ,$val,$limit_time=null){  
  $limit_time = $limit_time ? $limit_time : $this->limit_time;
  $file = $this->cache_dir."/".$key.".cache";
  $val = serialize($val);
  @file_put_contents($file,$val) or $this->error(__line__,"fail to write in file");
  @chmod($file,0777);
  @touch($file,time()+$limit_time) or $this->error(__line__,"fail to change time");
 }


 //读取缓存
 function __get($key){
  return $this->_get($key);
 }
 function _get($key){
  $file = $this->cache_dir."/".$key.".cache";
  if (@filemtime($file)>=time()){
   return unserialize(file_get_contents($file));
  }else{
   @unlink($file) or $this->error(__line__,"fail to unlink");
   return false;
  }
 }


 //删除缓存文件
 function __unset($key){
  return $this->_unset($key);
 }
 function _unset($key){
  if (@unlink($this->cache_dir."/".$key.".cache")){
   return true;
  }else{
   return false;
  }
 }


 //检查缓存是否存在,过期则认为不存在
 function __isset($key){
  return $this->_isset($key);
 }
 function _isset($key){
  $file = $this->cache_dir."/".$key.".cache";
  if (@filemtime($file)>=time()){
   return true;
  }else{
   @unlink($file) ;
   return false;
  }
 }


 //清除过期缓存文件
 function clear(){
  $files = scandir($this->cache_dir);
  foreach ($files as $val){
   if (filemtime($this->cache_dir."/".$val)<time()){
    @unlink($this->cache_dir."/".$val);
   }
  }
 }


 //清除所有缓存文件
 function clear_all(){
  $files = scandir($this->cache_dir);
  foreach ($files as $val){
   @unlink($this->cache_dir."/".$val);
  }
 }
 
 function error($msg,$debug = false) {
  $err = new Exception($msg);
  $str = "<pre>
<span style='color:red'>error:</span>
".print_r($err->getTrace(),1)."
</pre>";
  if($debug == true) {
   file_put_contents(date('Y-m-d H_i_s').".log",$str);
   return $str;
  }else{
   die($str);
  }
 }
}
?>

例2.从CI社区的stblog和CI的file_helper类中提取出来的php文件缓存类,一个简单的基于文件的key->value缓存类。

这个类可以用来缓存一些基本信息,比如博客的header,footer,sidebar中的一些不经常变化,从数据库中取出的

内容,取数据前先判断文件缓存中的内容是否过期,如果没过期取出来,过期了则连接数据库查询,并将结果重新

写入文件缓存,更新过期时间。跟memcache使用类似,不过更方便。用在一些小的应用上足够了...代码如下

 代码如下 复制代码

<?php
define('DIRECTORY_SEPARATOR','/');
define('FOPEN_WRITE_CREATE_DESTRUCTIVE','wb');
define('FOPEN_WRITE_CREATE','ab');
define('DIR_WRITE_MODE', 0777);
class FileCache {

 /**
     * 缓存路径
     *
     * @access private
     * @var string
     */
 private $_cache_path;

 /**
     * 缓存过期时间,单位是秒second
     *
     * @access private
     * @var int
     */
 private $_cache_expire;
 
 /**
     * 解析函数,设置缓存过期实践和存储路径
     *
     * @access public
     * @return void
     */
 public function __construct($expire, $cache_path)
 {
  $this->_cache_expire = $expire;
  $this->_cache_path = $cache_path;
 }
 
 /**
     * 缓存文件名
     *
     * @access public
     * @param  string $key
     * @return void
     */
 private function _file($key)
 {
  return $this->_cache_path . md5($key);
 }
 
 /**
     * 设置缓存
     *
     * @access public
     * @param  string $key 缓存的唯一键
     * @param  string $data 缓存的内容
     * @return bool
     */
 public function set($key, $data)
 {
  $value = serialize($data);
 
  $file = $this->_file($key);
 
     return $this->write_file($file, $value);
 }
 
 /**
     * 获取缓存
     *
     * @access public
     * @param  string $key 缓存的唯一键
     * @return mixed
     */
 public function get($key)
 {
  $file = $this->_file($key);
 
  /** 文件不存在或目录不可写 */
  if (!file_exists($file) || !$this->is_really_writable($file))
  {
   return false;
  }
 
  /** 缓存没有过期,仍然可用 */
  if ( time() < (filemtime($file) + $this->_cache_expire) )
  {
  
   $data = $this->read_file($file);
  
   if(FALSE !== $data)
   {
    return unserialize($data);
   }
  
   return FALSE;
  }
 
  /** 缓存过期,删除之 */
  @unlink($file);
  return FALSE;
  }
 
  function read_file($file)
 {
  if ( ! file_exists($file))
  {
   return FALSE;
  }
 
  if (function_exists('file_get_contents'))
  {
   return file_get_contents($file); 
  }

  if ( ! $fp = @fopen($file, FOPEN_READ))
  {
   return FALSE;
  }
 
  flock($fp, LOCK_SH);//读取之前加上共享锁
 
  $data = '';
  if (filesize($file) > 0)
  {
   $data =& fread($fp, filesize($file));
  }

  flock($fp, LOCK_UN);//释放锁
  fclose($fp);

  return $data;
 }
 
  function write_file($path, $data, $mode = FOPEN_WRITE_CREATE_DESTRUCTIVE)
 {
  if ( ! $fp = @fopen($path, $mode))
  {
   return FALSE;
  }
 
  flock($fp, LOCK_EX);
  fwrite($fp, $data);
  flock($fp, LOCK_UN);
  fclose($fp);
 
  return TRUE;
 }
 function is_really_writable($file)//兼容各平台判断文件是否有写入权限
 {
  // If we're on a Unix server with safe_mode off we call is_writable
  if (DIRECTORY_SEPARATOR == '/' AND @ini_get("safe_mode") == FALSE)
  {
   return is_writable($file);
  }
 
  // For windows servers and safe_mode "on" installations we'll actually
  // write a file then read it.  Bah...
  if (is_dir($file))
  {
   $file = rtrim($file, '/').'/'.md5(rand(1,100));
 
   if (($fp = @fopen($file, FOPEN_WRITE_CREATE)) === FALSE)
   {
    return FALSE;
   }
 
   fclose($fp);
   @chmod($file, DIR_WRITE_MODE);
   @unlink($file);
   return TRUE;
  }
  elseif (($fp = @fopen($file, FOPEN_WRITE_CREATE)) === FALSE)
  {
   return FALSE;
  }
 
  fclose($fp);
  return TRUE;
 }
}
$cache = new FileCache(30,'cache/');
$cache->set('test','this is a test.');
print $cache->get('test');
/* End of file FlieCache.php */


 

例3.自己觉得很好用的php文件缓存

 代码如下 复制代码

<?php
class cache

 private static $_instance = null;

    protected $_options = array(
        'cache_dir'        => "./",
        'file_name_prefix' => 'cache',
     'mode'            => '1', //mode 1 为serialize model 2为保存为可执行文件
    ); 
 
 /**
  * 得到本类实例
  *
  * @return Ambiguous
  */
 public static function getInstance()
 {
  if(self::$_instance === null)
  {
   self::$_instance = new self();
  }
  return self::$_instance;
 }
 
 /**
  * 得到缓存信息
  *
  * @param string $id
  * @return boolean|array
  */
 public static function get($id)
 {
  $instance = self::getInstance();
  
  //缓存文件不存在
  if(!$instance->has($id))
  {
   return false;
  }
  
  $file = $instance->_file($id);
  
  $data = $instance->_fileGetContents($file);
  
  if($data['expire'] == 0 || time() < $data['expire'])
  {
   return $data['contents'];
  }
  return false;
 }
 
 /**
  * 设置一个缓存
  *
  * @param string $id   缓存id
  * @param array  $data 缓存内容
  * @param int    $cacheLife 缓存生命 默认为0无限生命
  */
 public static function set($id, $data, $cacheLife = 0)
 {
  $instance = self::getInstance();
  
  $time = time();
  $cache      = array();
  $cache['contents'] = $data;
  $cache['expire']   = $cacheLife === 0 ? 0 : $time + $cacheLife;
  $cache['mtime']    = $time;
  
  $file = $instance->_file($id);
  
  return $instance->_filePutContents($file, $cache);
 }
 
    /**
     * 清除一条缓存
     *
     * @param string cache id 
     * @return void
     */  
 public static function delete($id)
 {
  $instance = self::getInstance();
  
  if(!$instance->has($id))
  {
   return false;
  }
     $file = $instance->_file($id);
     //删除该缓存
     return unlink($file);
 }
 
 /**
  * 判断缓存是否存在
  *
  * @param string $id cache_id
  * @return boolean true 缓存存在 false 缓存不存在
  */
 public static function has($id)
 {
  $instance = self::getInstance();
  $file     = $instance->_file($id);
  
  if(!is_file($file))
  {
   return false;
  }
  return true;
 }
 
 /**
  * 通过缓存id得到缓存信息路径
  * @param string $id
  * @return string 缓存文件路径
  */
 protected function _file($id)
 {
  $instance  = self::getInstance();
  $fileNmae  = $instance->_idToFileName($id);
  return $instance->_options['cache_dir'] . $fileNmae;
 } 
 
 /**
  * 通过id得到缓存信息存储文件名
  *
  * @param  $id
  * @return string 缓存文件名
  */
 protected function _idToFileName($id)
 {
  $instance  = self::getInstance();
  $prefix    = $instance->_options['file_name_prefix'];
  return $prefix . '---' . $id;
 }
 
 /**
  * 通过filename得到缓存id
  *
  * @param  $id
  * @return string 缓存id
  */
 protected function _fileNameToId($fileName)
 {
  $instance  = self::getInstance();
  $prefix    = $instance->_options['file_name_prefix'];
  return preg_replace('/^' . $prefix . '---(.*)$/', '$1', $fileName);
 }
 
 /**
  * 把数据写入文件
  *
  * @param string $file 文件名称
  * @param array  $contents 数据内容
  * @return bool
  */
 protected function _filePutContents($file, $contents)
 {
  if($this->_options['mode'] == 1)
  {
   $contents = serialize($contents);
  }
  else
  {
   $time = time(); 
         $contents = "<?phpn".
                 " // mktime: ". $time. "n".
                 " return ".
                 var_export($contents, true).
                 "n?>";
  }
  
  $result = false;
     $f = @fopen($file, 'w');
        if ($f) {
            @flock($f, LOCK_EX);
            fseek($f, 0);
            ftruncate($f, 0);
            $tmp = @fwrite($f, $contents);
            if (!($tmp === false)) {
                $result = true;
            }
            @fclose($f);
        }
  @chmod($file,0777);
  return $result;    
 }
 
 /**
  * 从文件得到数据
  *
  * @param  sring $file
  * @return boolean|array
  */
 protected function _fileGetContents($file)
 {
  if(!is_file($file))
  {
   return false;
  }
  
  if($this->_options['mode'] == 1)
  {
   $f = @fopen($file, 'r');
   @$data = fread($f,filesize($file));
   @fclose($f);
   return unserialize($data);
  }
  else
  {
   return include $file;
  }
 }
 
 /**
  * 构造函数
  */
 protected function __construct()
 {
 
 }
 
 /**
  * 设置缓存路径
  *
  * @param string $path
  * @return self
  */
 public static function setCacheDir($path)
 {
  $instance  = self::getInstance();
        if (!is_dir($path)) {
            exit('file_cache: ' . $path.' 不是一个有效路径 ');
        }
        if (!is_writable($path)) {
            exit('file_cache: 路径 "'.$path.'" 不可写');
        }
   
        $path = rtrim($path,'/') . '/';
        $instance->_options['cache_dir'] = $path;
       
        return $instance;
 }
 
 /**
  * 设置缓存文件前缀
  *
  * @param srting $prefix
  * @return self
  */
 public static function setCachePrefix($prefix)
 {
  $instance  = self::getInstance();
  $instance->_options['file_name_prefix'] = $prefix;
  return $instance;
 }
 
 /**
  * 设置缓存存储类型
  *
  * @param int $mode
  * @return self
  */
 public static function setCacheMode($mode = 1)
 {
  $instance  = self::getInstance();
  if($mode == 1)
  {
   $instance->_options['mode'] = 1;
  }
  else
  {
   $instance->_options['mode'] = 2;
  }
  
  return $instance;
 }
 
 /**
  * 删除所有缓存
  * @return boolean
  */
 public static function flush()
 {
  $instance  = self::getInstance();
  $glob = @glob($instance->_options['cache_dir'] . $instance->_options['file_name_prefix'] . '--*');
  
  if(empty($glob))
  {
   return false;
  }
  
  foreach ($glob as $v)
  {
   $fileName = basename($v);
   $id =  $instance->_fileNameToId($fileName);
   $instance->delete($id);
  }
  return true;
 }
}

/* 初始化设置cache的配置信息什么的 */
cache::setCachePrefix('core'); //设置缓存文件前缀
cache::setCacheDir('./cache'); //设置存放缓存文件夹路径

//模式1 缓存存储方式
//a:3:{s:8:"contents";a:7:{i:0;i:1;i:1;i:2;i:2;i:3;i:3;i:34;i:4;i:5;i:5;i:6;i:6;i:6;}s:6:"expire";i:0;s:5:"mtime";i:1318218422;}
//模式2 缓存存储方式
/*
 <?php
 // mktime: 1318224645
 return array (
  'contents' =>
  array (
    0 => 1,
    1 => 2,
    2 => 3,
    3 => 34,
    4 => 5,
    5 => 6,
    6 => 6,
  ),
  'expire' => 0,
  'mtime' => 1318224645,
)
?>
 *
 *
 */
cache::setCacheMode('2');

if(!$row = cache::get('zj2'))
{
 
 $array = array(1,2,3,34,5,6,6);
 $row = cache::set('zj2',$array);
}
// cache::flush(); 清空所有缓存

print_r($row);
 
件缓存 class    

<?php
/**
 * 文件缓存类
 * @author  xiaojiong & 290747680@qq.com
 * @date 2011-08-17
 */
class cache
{
 const FILE_LIFE_KEY = 'FILE_LIFE_KEY';
 
 const CLEAR_ALL_KEY = 'CLEAR_ALL';
 
    static $_instance = null;
 
    protected $_options = array(
        'cache_dir' => './cache',
        'file_locking' => true,
        'file_name_prefix' => 'cache',
        'cache_file_umask' => 0777,
     'file_life'  => 100000
    );
   
    static function &getInstance($options = array())
    {
     if(self::$_instance === null)
     {
      self::$_instance = new self($options);
     } 
     return self::$_instance;
    }
   
    /**
     * 设置参数
     * @param  array $options 缓存参数
     * @return void
     */
 static function &setOptions($options = array())
 {
         return self::getInstance($options);
 }
 
    /**
     * 构造函数
     * @param  array $options 缓存参数
     * @return void
     */
    private function __construct($options = array())
    {  
        if ($this->_options['cache_dir'] !== null) {
   
   $dir = rtrim($this->_options['cache_dir'],'/') . '/';
         $this->_options['cache_dir'] = $dir;
        
   if (!is_dir($this->_options['cache_dir'])) {
             mkdir($this->_options['cache_dir'],0777,TRUE);
         }
         if (!is_writable($this->_options['cache_dir'])) {
             exit('file_cache: 路径 "'. $this->_options['cache_dir'] .'" 不可写');
         }
     
        } else {
           exit('file_cache: "options" cache_dir 不能为空 ');
        }
    }

    /**
     * 设置缓存路径
     * @param  string  $value
     * @return void
     */
    static function setCacheDir($value)
    {
     $self = & self::getInstance();
     
        if (!is_dir($value)) {
            exit('file_cache: ' . $value.' 不是一个有效路径 ');
        }
        if (!is_writable($value)) {
            exit('file_cache: 路径 "'.$value.'" 不可写');
        }
   
        $value = rtrim($this->_options['cache_dir'],'/') . '/';
       
        $self->_options['cache_dir'] = $value;
    }
   
    /**
     * 存入缓存数据
     * @param  array  $data          放入缓存的数据
     * @param  string $id            缓存id(又名缓存识别码)
     * @param  cache_life            缓存时间
     * @return boolean True if no problem
     */
    static function save($data, $id = null, $cache_life = null)
    {
     $self = & self::getInstance();
        if (!$id) {
            if ($self->_id) {
                $id = $self->_id;
            } else {
                exit('file_cache:save() id 不能为空!');
            }
        }
        $time = time();
       
        if($cache_life) {
         $data[self::FILE_LIFE_KEY] = $time + $cache_life;
        }
  elseif
  ($cache_life != 0){
         $data[self::FILE_LIFE_KEY] = $time + $self->_options['file_life'];
        }
       
        $file = $self->_file($id);
       
        $data = "<?phpn".
                " // mktime: ". $time. "n".
                " return ".
                var_export($data, true).
                "n?>"
                ;
       
        $res = $self->_filePutContents($file, $data);
        return $res;
    }
   
   
    /**
     * 得到缓存信息
     *
     * @param  string  $id  缓存id
     * @return string|array 缓存数据
     */
    static function load($id)
    {
        $self = & self::getInstance();
     $time = time();
     //检测缓存是否存在
     if (!$self->test($id)) {
            // The cache is not hit !
            return false;
        }
       
  //全部清空识别文件
        $clearFile = $self->_file(self::CLEAR_ALL_KEY);
  
  $file = $self->_file($id);
  
        //判断缓存是否已被全部清除
     if(is_file($clearFile) && filemtime($clearFile) > filemtime($file))
     {
      return false;
     }
      
        $data = $self->_fileGetContents($file);
      if(empty($data[self::FILE_LIFE_KEY]) || $time < $data[self::FILE_LIFE_KEY]) {
            unset($data[self::FILE_LIFE_KEY]);
       return $data;   
      }
      return false;
    }   
   
    /**
     * 写入缓存文件
     *
     * @param  string $file   缓存路径
     * @param  string $string 缓存信息
     * @return boolean true 成功
     */
    protected function _filePutContents($file, $string)
    {
     $self = & self::getInstance();
        $result = false;
        $f = @fopen($file, 'ab+');
        if ($f) {
            if ($self->_options['file_locking']) @flock($f, LOCK_EX);
            fseek($f, 0);
            ftruncate($f, 0);
            $tmp = @fwrite($f, $string);
            if (!($tmp === false)) {
                $result = true;
            }
            @fclose($f);
        }
        @chmod($file, $self->_options['cache_file_umask']);
        return $result;
    }
   
    /**
     * 格式化后的缓存文件路径
     *
     * @param  string $id 缓存id
     * @return string 缓存文件名(包括路径)
     */
    protected function _file($id)
    {
     $self = & self::getInstance();
        $fileName = $self->_idToFileName($id);
        return $self->_options['cache_dir'] . $fileName;
    }   
   
    /**
     * 格式化后的缓存文件名字
     *
     * @param  string $id 缓存id
     * @return string 缓存文件名
     */
    protected function _idToFileName($id)
    {
     $self = & self::getInstance();
        $self->_id = $id;
        $prefix = $self->_options['file_name_prefix'];
        $result = $prefix . '---' . $id;
        return $result;
    }  
   
    /**
     * 判断缓存是否存在
     *
     * @param  string $id Cache id
     * @return boolean True 缓存存在 False 缓存不存在
     */
    static function test($id)
    {
     $self = & self::getInstance();
        $file = $self->_file($id);
       
        if (!is_file($file)) {
            return false;
        }
       
        return true;
    }
   
    /**
     * 得到缓存信息
     *
     * @param  string $file 缓存路径
     * @return string 缓存内容
     */
    protected function _fileGetContents($file)
    {
        if (!is_file($file)) {
            return false;
        }
        return include $file;
    }    
   
    /**
     * 清除所有缓存
     *
     * @return void
     */   
    static function clear()
    {
     $self = & self::getInstance();
     $self->save('CLEAR_ALL',self::CLEAR_ALL_KEY); 
    }  
 
    /**
     * 清除一条缓存
     *
     * @param string cache id 
     * @return void
     */  
    static function del($id)
    {
  $self = & self::getInstance();
     if(!$self->test($id)){
      // 该缓存不存在
      return false;
     }
     $file = $self->_file($id);
     return unlink($file);
    } 
}

存入数据

<?php
$config = array(
 'name' => 'xiaojiong',
 'qq'   => '290747680',
 'age'  => '20',
);

//第一个参数 缓存data
//第二个参数 缓存id
//第三个参数 cache_life 0 永不过期(cache::clear()清空所有除外) 默认cache_life 为option_cache_life
cache::save($config,'config',0);

载入数据

<?php
//只有一个参数 cache_id
$config = cache::load('config');

清空缓存

<?php
//清空指定缓存
cache::del('config');
//清空所有缓存
cache::clear();

cache信息配置

//在执行所有cache_func前调用

$_options = array(
    'cache_dir' => './cache', //缓存文件目录
    'file_name_prefix' => 'cache',//缓存文件前缀
    'file_life'  => 100000, //缓存文件生命
);
cache::setOptions($options);

//再执行 就会按着新配置信息执行,否则是默认信息
cache::save($arr,'arr');


//就是这个方法 貌似不合理 望大家指点

在php中生成zip文件我们只要使用一个php zip压缩ZipArchive函数就可以了,下面小编来给大家总结两个实现一个是利用ZipArchive生成zip,另一个压缩文件夹下所有文件。

注意:

ZipArchive来压缩文件。这个是php的扩展类,自php5.2版本以后就已经支持这个扩展,如果你在使用的时候出现错误,查看下php.ini里面的extension=php_zip.dll前面的分号有没有去掉,然后再重启Apache这样才能使用这个类库。

例1

生成zip 压缩文件

 代码如下 复制代码

<?php
/* 生成zip 压缩文件 */
function create_zip($files = array(),$destination = '',$overwrite = false) {
    //if the zip file already exists and overwrite is false, return false
    if(file_exists($destination) && !$overwrite) { return false; }
    //vars
    $valid_files = array();
    //if files were passed in...
    if(is_array($files)) {
        //cycle through each file
        foreach($files as $file) {
            //make sure the file exists
            if(file_exists($file)) {
                $valid_files[] = $file;
            }
        }
    }
    //if we have good files...
    if(count($valid_files)) {
        //create the archive
        $zip = new ZipArchive();
        if($zip->open($destination,$overwrite ? ZIPARCHIVE::OVERWRITE : ZIPARCHIVE::CREATE) !== true) {
            return false;
        }
        //add the files
        foreach($valid_files as $file) {
            $file_info_arr= pathinfo($file);
            $zip->addFile($file,$file_info_arr['basename']);//去掉层级目录
        }
        //debug
        //echo 'The zip archive contains ',$zip->numFiles,' files with a status of ',$zip->status;
 
        //close the zip -- done!
        $zip->close();
 
        //check to make sure the file exists
        return file_exists($destination);
    }
    else
    {
        return false;
    }
}
 
define('ROOTPATH',dirname ( __FILE__ )); //网站路径
 
$files_to_zip = array(
    ROOTPATH.DIRECTORY_SEPARATOR.'PHP+jQuery+Cookbook.pdf',
    ROOTPATH.DIRECTORY_SEPARATOR.'TurboListerZeroTemplate.csv'
);
//if true, good; if false, zip creation failed
$filename='my-archive.zip';
$result = create_zip($files_to_zip,$filename);

例2

压缩文件夹下面的所有文

 代码如下 复制代码

<?php
/*
php zip压缩文件夹下面的所有文件
*/
class HZip
{
  /**
   * 添加文件和子目录的文件到zip文件
   * @param string $folder
   * @param ZipArchive $zipFile
   * @param int $exclusiveLength Number of text to be exclusived from the file path.
   */
  private static function folderToZip($folder, &$zipFile, $exclusiveLength) {
    $handle = opendir($folder);
    while (false !== $f = readdir($handle)) {
      if ($f != '.' && $f != '..') {
        $filePath = "$folder/$f";
        // Remove prefix from file path before add to zip.
        $localPath = substr($filePath, $exclusiveLength);
        if (is_file($filePath)) {
          $zipFile->addFile($filePath, $localPath);
        } elseif (is_dir($filePath)) {
          // 添加子文件夹
          $zipFile->addEmptyDir($localPath);
          self::folderToZip($filePath, $zipFile, $exclusiveLength);
        }
      }
    }
    closedir($handle);
  }
 
  /**
   * Zip a folder (include itself).
   * Usage:
   *   HZip::zipDir('/path/to/sourceDir', '/path/to/out.zip');
   *
   * @param string $sourcePath Path of directory to be zip.
   * @param string $outZipPath Path of output zip file.
   */
  public static function zipDir($sourcePath, $outZipPath)
  {
    $pathInfo = pathInfo($sourcePath);
    $parentPath = $pathInfo['dirname'];
    $dirName = $pathInfo['basename'];
    $sourcePath=$parentPath.'/'.$dirName;//防止传递'folder' 文件夹产生bug
    $z = new ZipArchive();
    $z->open($outZipPath, ZIPARCHIVE::CREATE);//建立zip文件
    $z->addEmptyDir($dirName);//建立文件夹
    self::folderToZip($sourcePath, $z, strlen("$parentPath/"));
    $z->close();
  }
}
 
//使用方法
HZip::zipDir('yourlife', 'yourlife.zip');
?>

/******** ziparchive 可选参数 *******/
/*
1.ZipArchive::addEmptyDir

添加一个新的文件目录

2.ZipArchive::addFile

将文件添加到指定zip压缩包中。

3.ZipArchive::addFromString

添加的文件同时将内容添加进去

4.ZipArchive::close

关闭ziparchive

5.ZipArchive::extractTo

将压缩包解压

6.ZipArchive::open

打开一个zip压缩包

7.ZipArchive::getStatusString

返回压缩时的状态内容,包括错误信息,压缩信息等等

8.ZipArchive::deleteIndex

删除压缩包中的某一个文件,如:deleteIndex(0)删除第一个文件

9.ZipArchive::deleteName

删除压缩包中的某一个文件名称,同时也将文件删除。
......
*/

[!--infotagslink--]

相关文章

  • SpringBoot实现excel文件生成和下载

    这篇文章主要为大家详细介绍了SpringBoot实现excel文件生成和下载,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下...2021-02-09
  • js导出table数据到excel即导出为EXCEL文档的方法

    复制代码 代码如下: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta ht...2013-10-13
  • c#读取excel方法实例分析

    这篇文章主要介绍了c#读取excel方法,实例分析了C#读取excel文件的原理与相关技巧,需要的朋友可以参考下...2020-06-25
  • Python导入数值型Excel数据并生成矩阵操作

    这篇文章主要介绍了Python导入数值型Excel数据并生成矩阵操作,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...2020-06-09
  • C# 导出Excel的6种简单方法实现

    C# 导出 Excel 的6种简单方法:数据表导出到 Excel,对象集合导出到 Excel,数据库导出到 Excel,微软网格控件导出到 Excel,数组导出到 Excel,CSV 导出到 Excel,你都会了吗?需要的朋友们下面随着小编来一起学习学习吧...2020-06-25
  • C# winform打开Excel文档的方法总结(必看篇)

    下面小编就为大家带来一篇C# winform打开Excel文档的方法总结(必看篇)。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧...2020-06-25
  • C#实现Excel表数据导入Sql Server数据库中的方法

    这篇文章主要介绍了C#实现Excel表数据导入Sql Server数据库中的方法,结合实例形式详细分析了C#读取Excel表数据及导入Sql Server数据库的具体操作步骤与相关操作技巧,需要的朋友可以参考下...2020-06-25
  • C#实现将数据导出到word或者Excel中的方法

    这篇文章主要介绍了C#实现将数据导出到word或者Excel中的方法,涉及C#操作word及Excel格式文件的方法,具有一定参考借鉴价值,需要的朋友可以参考下...2020-06-25
  • C#使用Ado.Net更新和添加数据到Excel表格的方法

    这篇文章主要介绍了C#使用Ado.Net更新和添加数据到Excel表格的方法,较为详细的分析了OLEDB的原理与使用技巧,可实现较为方便的操作Excel数据,需要的朋友可以参考下...2020-06-25
  • R语言导入导出数据的几种方法汇总

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

    这篇文章主要为大家详细介绍了C#使用Aspose.Cells创建和读取Excel文件,具有一定的参考价值,感兴趣的小伙伴们可以参考一下...2020-06-25
  • C#使用oledb导出数据到excel的方法

    这篇文章主要介绍了C#使用oledb导出数据到excel的方法,结合实例形式分析了C#操作oledb导出数据的相关技巧与注意事项,需要的朋友可以参考下...2020-06-25
  • C#操作excel打印的示例

    这篇文章主要介绍了C#操作excel打印的示例,帮助大家利用c#打印表格,提高办公效率,感兴趣的朋友可以了解下...2020-12-08
  • C#删除Excel中的图片实例代码

    在本篇文章里小编给大家分享了关于C#删除Excel中的图片的实例代码内容,有兴趣的朋友们参考学习下。...2020-06-25
  • C#使用Aspose.Cells控件读取Excel

    本文介绍Aspose.Cells基础的用法,供大家参考。...2020-06-25
  • C#中将ListView中数据导出到Excel的实例方法

    首先 你需要添加引用Microsoft Excel 11.0 Object Library...2020-06-25
  • python3 循环读取excel文件并写入json操作

    这篇文章主要介绍了python3 循环读取excel文件并写入json操作,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...2020-07-14
  • C# WinForm导出Excel方法介绍

    在.NET应用中,导出Excel是很常见的需求,导出Excel报表大致有以下三种方式:Office PIA,文件流和NPOI开源库,本文只介绍前两种方式...2020-06-25
  • python操作mysql、excel、pdf的示例

    这篇文章主要介绍了python操作mysql、excel、pdf的示例,帮助大家更好的理解和学习使用python,感兴趣的朋友可以了解下...2021-03-29
  • C#将Excel转成PDF的方法

    今天小编就为大家分享一篇关于C#将Excel转成PDF的方法,小编觉得内容挺不错的,现在分享给大家,具有很好的参考价值,需要的朋友一起跟随小编来看看吧...2020-06-25