• 技术文章 >后端开发 >php教程

    直接可以拿来用的PHP惯用功能代码片段(6~10)

    2016-06-13 12:34:47原创274
    直接可以拿来用的PHP常用功能代码片段(6~10)

    文章来源:jquery教程?-?http://www.jq-school.com/Show.aspx?id=324

    ?

    前面已经分享了PHP常用功能代码片段(1~5),今天是第二篇,也就是第六到十这5个实现代码片段,希望可以帮到jquery学堂群里面的成员和广大对PHP开发的网友们提高开发效率,以下是第二篇文章。

    6、PHP实现zip压缩解压通用函数

    function ezip($zip, $hedef = ''){
        $dirname=preg_replace('/.zip/', '', $zip);
        $root = $_SERVER['DOCUMENT_ROOT'].'/zip/';
        // echo $root. $zip;
        $zip = zip_open($root . $zip);
        // var_dump($zip);
        @mkdir($root . $hedef . $dirname.'//m.sbmmt.com/m/'.$zip_dosya);
        while($zip_icerik = zip_read($zip)){
    
            $zip_dosya = zip_entry_name($zip_icerik);
            if(strpos($zip_dosya, '.')){
                $hedef_yol = $root . $hedef . $dirname.'//m.sbmmt.com/m/'.$zip_dosya;
                @touch($hedef_yol);
                // echo $hedef_yol;
                $yeni_dosya = @fopen($hedef_yol, 'w+');
                @fwrite($yeni_dosya, zip_entry_read($zip_icerik));
                @fclose($yeni_dosya); 
                // $yeni_dosya;
    
            }else{
                @mkdir($root . $hedef . $dirname.'//m.sbmmt.com/m/'.$zip_dosya);
                // echo $root . $hedef . 'x/'.$zip_dosya;
            };
        };
    }
    // ezip('yuol.zip','./tr/');
    
    function zip($path) {
        $path=preg_replace('/\/$/', '', $path);
        preg_match('/\/([\d\D][^\/]*)$/', $path, $matches, PREG_OFFSET_CAPTURE);
        $filename=$matches[1][0].".zip";
        // var_dump($filename);
        // set_time_limit(0);
        $zip = new ZipArchive();
        $zip->open($filename,ZIPARCHIVE::OVERWRITE);//return ;
        // var_dump($path);
        if (is_file($path)) {
            $path=preg_replace('/\/\//', '//m.sbmmt.com/m/', $path);
            $base_dir=preg_replace('/\/[\d\D][^\/]*$/', '//m.sbmmt.com/m/', $path);
            $base_dir=addcslashes($base_dir, '/:');
    
            $localname=preg_replace('//m.sbmmt.com/m/'.$base_dir.'//m.sbmmt.com/m/', '', $path);
            // var_dump($localname);
            $zip->addFile($path,$localname);
            // var_dump($path);
            $zip->close();
            return;
        }elseif (is_dir($path)) {
            $path=preg_replace('/\/[\d\D][^\/]*$/', '', $path);
            $base_dir=$path.'//m.sbmmt.com/m/';//基目录
            $base_dir=addcslashes($base_dir, '/:');
            // var_dump($base_dir);
        }
        $path=preg_replace('/\/\//', '//m.sbmmt.com/m/', $path);
        // var_dump($path);
        function addItem($path,&$zip,&$base_dir){
            // var_dump($path);
            $handle = opendir($path);
            // var_dump($path);
            while (false !== ($file = readdir($handle))) {
                if (($file!='.')&&($file!='..')){
                    // var_dump($file);
                    $ipath=$path.'//m.sbmmt.com/m/'.$file;
                    if (is_file($ipath)){//条目是文件
                        $localname=preg_replace('//m.sbmmt.com/m/'.$base_dir.'//m.sbmmt.com/m/', '', $ipath);
                        var_dump($localname);
                        $zip->addFile($ipath,$localname);
                        // var_dump($r);
                    } else if (is_dir($ipath)){
                        addItem($ipath,$zip,$base_dir);
                        $localname=preg_replace('//m.sbmmt.com/m/'.$base_dir.'//m.sbmmt.com/m/', '', $ipath);
                        var_dump($localname);
                        $zip->addEmptyDir($localname);
                    }
                    // var_dump($path);
                }
            }
        }
        // var_dump($base_dir);
        addItem($path,$zip,$base_dir);
        $zip->close();
    }
    //调用方法
    zip('解压的目录');


    7、php实用获取远程图片的通用方法

    function auto_save_image($body){
    	$img_array = explode('&',$body);
    	/*$img_array = array();
    	preg_match_all("/(src)=[\"|\'| ]{0,}(http:\/\/(.*)\.(gif|jpg|jpeg|bmp|png))[\"|\'| ]{0,}/isU", $body, $img_array);
    	$img_array = array_unique($img_array[2]);*/ //也可以自动匹配
    	set_time_limit(0);
    	$imgPath = "uploads/allimg/".date("Ymd")."//m.sbmmt.com/m/";
    	$milliSecond = strftime("%H%M%S",time());
    	if(!is_dir($imgPath)) @mkdir($imgPath,0777);
    	foreach($img_array as $key =>$value)
    	{
    			$value = trim($value);
    			$get_file = @file_get_contents($value);
    			$rndFileName = $imgPath."//m.sbmmt.com/m/".$milliSecond.$key.".".substr($value,-3,3);
    			if($get_file)
    			{
    					$fp = @fopen($rndFileName,"w");
    					@fwrite($fp,$get_file);
    					@fclose($fp);
    			}
    			$body = @ereg_replace($value, $rndFileName, $body);
    	} 
    	return $body;
    }


    8、PHP实现简单的文件下载通用方法

    function download_file($file){
    	if(is_file($file)){
    		$length = filesize($file);
    		$type = mime_content_type($file);
    		$showname =  ltrim(strrchr($file,'//m.sbmmt.com/m/'),'//m.sbmmt.com/m/');
    		header("Content-Description: File Transfer");
    		header('Content-type: ' . $type);
    		header('Content-Length:' . $length);
    		if (preg_match('/MSIE/', $_SERVER['HTTP_USER_AGENT'])) { //for IE
    		 header('Content-Disposition: attachment; filename="' . rawurlencode($showname) . '"');
    		} else {
    		 header('Content-Disposition: attachment; filename="' . $showname . '"');
    		}
    		readfile($file);
    		exit;
    	} else {
    	 exit('文件已被删除!');
    	}
    }


    9、PHP实现导出Excel文件通用方法

    /**
        * 导出数据为excel表格
        *@param $data    一个二维数组,结构如同从数据库查出来的数组
        *@param $title   excel的第一行标题,一个数组,如果为空则没有标题
        *@param $filename 下载的文件名
        *@examlpe 
        $stu = M ('User');
        $arr = $stu -> select();
        exportexcel($arr,array('id','账户','密码','昵称'),'文件名!');
    */
    function exportexcel($data=array(),$title=array(),$filename='report'){
        header("Content-type:application/octet-stream");
        header("Accept-Ranges:bytes");
        header("Content-type:application/vnd.ms-excel");  
        header("Content-Disposition:attachment;filename=".$filename.".xls");
        header("Pragma: no-cache");
        header("Expires: 0");
        //导出xls 开始
        if (!empty($title)){
            foreach ($title as $k => $v) {
                $title[$k]=iconv("UTF-8", "GB2312",$v);
            }
            $title= implode("\t", $title);
            echo "$title\n";
        }
        if (!empty($data)){
            foreach($data as $key=>$val){
                foreach ($val as $ck => $cv) {
                    $data[$key][$ck]=iconv("UTF-8", "GB2312", $cv);
                }
                $data[$key]=implode("\t", $data[$key]);
                
            }
            echo implode("\n",$data);
        }
    }


    10、PHP实现如何清除TP的文件缓存

    public function cache_clear() {
    	$this->deldir(TEMP_PATH);
    }
    function deldir($dir) {
    	$dh = opendir($dir);
    	while ($file = readdir($dh)) {
    		if ($file != "." && $file != "..") {
    			$fullpath = $dir . "//m.sbmmt.com/m/" . $file;
    			if (!is_dir($fullpath)) {
    				unlink($fullpath);
    			} else {
    				deldir($fullpath);
    			}
    		}
    	}
    }

    ?

    声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。
    专题推荐:zip path file dir dump
    上一篇: 高分在线XML解析 下一篇: PHP中对缓冲区的统制实现代码
    PHP编程就业班

    相关文章推荐

    • 面试官:列举几种PHP拓展的实现手段及其性能比较?• javascript - 哪里有可以下载的股票历史数据?• 日常整理PHP中简单的图形处理(经典)_php实例• php上传文件,创建递归目录的实例代码_php实例• 用PHP生成静态HTML速度快类库_php实例

    全部评论我要评论

  • 取消发布评论发送
  • 1/1

    PHP中文网