thinkphp开发常用的一些函数

1.导出excel

/**

* 导出excel

*@param$strTable    表格内容

*@param$filename 文件名

*/

function   downloadExcel($strTable,$filename)

{

        header("Content-type: application/vnd.ms-excel");

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

        header("Content-Disposition: attachment; filename=".$filename."_".date('Y-m-d').".xls");

        header('Expires:0');

        header('Pragma:public');

         echo''.$strTable.'';

}

2. array转xml

/*

* 作用:array转xml

*/

functionarrayToXml($arr)

{

         $xml="";

         foreach($arras$key=>$val) {

                if(is_numeric($val)) {

                        $xml.="<".$key.">".$val."";

            }else

                          $xml.="<".$key.">";

            }

                           $xml.="";

                       return$xml;

  }

3. 将xml转为array

/**

* 作用:将xml转为array

*/

functionxmlToArray($xml)

{

      //将XML转为array

      $array_data=json_decode(json_encode(simplexml_load_string($xml,'SimpleXMLElement',LIBXML_NOCDATA)),true);

       return$array_data;

}

4.随机生成字符串

/**

* 随机生成字符串

*

*/

functionrandStr($length=4,$type="1")

{

           $array=array(

            '1'=>'0123456789',

             '2'=>'ABCDEFGHIJKLMNOPQRSTUVWXYZ',

              '3'=>'0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz',

              );

         $string=$array[$type];

         $count=strlen($string)-1;

         $rand='';

         for($i=0;$i<$length;$i++) {

      $rand.=$string[mt_rand(0,$count)];

}

return$rand;

}

5.字节转换

functionsizeformat($bytesize)

{

           $i=0;

            //当$bytesize 大于是1024字节时,开始循环,当循环到第4次时跳出;

            while(abs($bytesize)>=1024) {

             $bytesize=$bytesize/1024;

              $i++;

              if($i==4)break;

}

      / /将Bytes,KB,MB,GB,TB定义成一维数组;

         $units=array("B","KB","MB","GB","TB");

        $newsize=round($bytesize,2);

         return("$newsize $units[$i]");

}

6.写入静态页面缓存

/**

* 写入静态页面缓存

*/

functionwrite_html_cache($html){

                  $html_cache_arr=C('HTML_CACHE_ARR');

                   $request=think\Request::instance();

                    $m_c_a_str=$request->module().'_'.$request->controller().'_'.$request->action();// 模块_控制器_方法

                     $m_c_a_str=strtolower($m_c_a_str);

                    //exit('write_html_cache写入缓存
');

        foreach($html_cache_arras$key=>$val)

       {

                $val['mca']=strtolower($val['mca']);

                if($val['mca']!=$m_c_a_str)//不是当前 模块 控制器 方法 直接跳过

                 continue;

             //if(!is_dir(RUNTIME_PATH.'html'))

            //mkdir(RUNTIME_PATH.'html');

           //$filename =  RUNTIME_PATH.'html'.DIRECTORY_SEPARATOR.$m_c_a_str;

           $filename=$m_c_a_str;

           // 组合参数

          if(isset($val['p']))

       {

              foreach($val['p']as$k=>$v)

              $filename.='_'.$_GET[$v];

        }

            $filename.='.html';

          \think\Cache::set($filename,$html);

         //file_put_contents($filename, $html);

}

}

7.读取静态页面缓存

/**

* 读取静态页面缓存

*/

functionread_html_cache(){

      $html_cache_arr=C('HTML_CACHE_ARR');

      $request=think\Request::instance();

      $m_c_a_str=$request->module().'_'.$request->controller().'_'.$request->action();// 模块_控制器_方法

      $m_c_a_str=strtolower($m_c_a_str);

      //exit('read_html_cache读取缓存
');

foreach($html_cache_arras$key=>$val)

{

           $val['mca']=strtolower($val['mca']);

            if($val['mca']!=$m_c_a_str)//不是当前 模块 控制器 方法 直接跳过

            continue;

            //$filename =  RUNTIME_PATH.'html'.DIRECTORY_SEPARATOR.$m_c_a_str;

              $filename=$m_c_a_str;

              // 组合参数

if(isset($val['p']))

{

           foreach($val['p']as$k=>$v)

          $filename.='_'.$_GET[$v];

}

$filename.='.html';

$html=\think\Cache::get($filename);

if($html)

{

            //echo file_get_contents($filename);

          echo\think\Cache::get($filename);

           exit();

}

}

}

8.格式化字节大小

/**

* 格式化字节大小

* @param  number $size      字节数

* @param  string $delimiter 数字和单位分隔符

* @return string            格式化后的带单位的大小

*/

function format_bytes($size, $delimiter = '') {

             $units = array('B', 'KB', 'MB', 'GB', 'TB', 'PB');

             for ($i = 0; $size >= 1024 && $i < 5; $i++) $size /= 1024;

                   return round($size, 2) . $delimiter . $units[$i];

}

9.获取最近时间

function getTime($time) {

$rtime = date("m-d H:i",$time);

$rtime2 = date("Y-m-d H:i",$time);

$htime = date("H:i",$time);

$time = time() - $time;

if ($time < 60) {

$str = '刚刚';

}

elseif ($time < 60 * 60) {

$min = floor($time/60);

$str = $min.' 分钟前';

}

elseif ($time < 60 * 60 * 24) {

$h = floor($time/(60*60));

$str = $h.'小时前 '.$htime;

}

elseif ($time < 60 * 60 * 24 * 3) {

$d = floor($time/(60*60*24));

if($d==1)

$str = '昨天 '.$htime;

else

$str = '前天 '.$htime;

}

elseif ($time < 60 * 60 * 24 * 7) {

$d = floor($time/(60*60*24));

$str = $d.' 天前 '.$htime;

} elseif ($time < 60 * 60 * 24 * 30) {

$str = $rtime;

}

else {

$str = $rtime2;

}

return $str;

}

10.字符串剪裁

function msubstr($str, $start = 0, $length, $charset = "utf-8", $suffix = false) {

if (function_exists("mb_substr")) {

if ($suffix)

return mb_substr($str, $start, $length, $charset) . "...";

else

return mb_substr($str, $start, $length, $charset);

}elseif (function_exists('iconv_substr')) {

if ($suffix)

return iconv_substr($str, $start, $length, $charset) . "...";

else

return iconv_substr($str, $start, $length, $charset);

}

$re['utf-8'] = "/[x01-x7f]|[xc2-xdf][x80-xbf]|[xe0-xef][x80-xbf]{2}|[xf0-xff][x80-xbf]{3}/";

$re['gb2312'] = "/[x01-x7f]|[xb0-xf7][xa0-xfe]/";

$re['gbk'] = "/[x01-x7f]|[x81-xfe][x40-xfe]/";

$re['big5'] = "/[x01-x7f]|[x81-xfe]([x40-x7e]|xa1-xfe])/";

preg_match_all($re[$charset], $str, $match);

$slice = join("", array_slice($match[0], $start, $length));

if ($suffix)

return $slice . "…";

return $slice;

}

11.将字符解析成数组

/**

* 将字符解析成数组

* @param $str

*/

function parseParams($str)

{

$arrParams = [];

parse_str(html_entity_decode(urldecode($str)), $arrParams);

return $arrParams;

}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 14,352评论 0 33
  • <?php /** * 常用函数库 * */ class Core_Fun { /** * 对变量进行反...
    寻梦xunm阅读 3,471评论 0 0
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,497评论 19 139
  • #微写作#第13篇 今天想聊一聊关于语音直播的这个话题。昨天晚上是社群的第一节课,我原本是打算用直播的方式来讲课,...
    SusanKuang阅读 3,535评论 4 5
  • 《你说怎么办》 我不喜欢喧嚣 愿意安静地活着 守着一口池塘 旁边一间简单的住房 池塘里养着四大家鱼 鱼肥了换菜换粮...
    风吟月影动阅读 1,196评论 0 0