찾다
백엔드 개발PHP 튜토리얼Codeigniter 生成静态页面_PHP教程

Codeigniter 生成静态页面_PHP教程

Jul 14, 2016 am 10:09 AM
codeigniter사용생성하다단순한법정읽다공전페이지

    使用CI来生成静态页面,其实很简单,就像论坛里面说的那样,读出页面中的数据,再写入html文件中,最后显示这个html文件就行了,好吧,上码。

 
 
[php] 
                
class MY_Loader extends CI_Loader {  
                    
    public function m_view($view, $vars = array(), $return = FALSE){  
        return $this->_m_ci_load(array('_ci_view' => $view, '_ci_vars' => $this->_ci_object_to_array($vars), '_ci_return' => $return));  
    }  
                    
    protected function _m_ci_load($_ci_data){  
          .....  
                      
            $_ci_html_file=($_ci_ext==='')? $_ci_view.".html" : $_ci_view;//这,生成静态页面的文件名   
                            
            foreach ($this->_ci_view_paths as $_ci_view_file => $cascade){  
                if (file_exists($_ci_view_file.$_ci_file)){  
                    $_ci_path = $_ci_view_file.$_ci_file;  
                    $_ci_html_path=$_ci_view_file.$_ci_html_file;//生成静态页面的路径   
                    $file_exists = TRUE;  
                    break;  
                }  
      ......  
            }  
        }  
                
     .......  
        //在这   
      if(config_item("html")===TRUE){//是否开启生成静态页面   
            $_html_file=@fopen($_ci_html_path,'r');//创建.html文件   
            $buffer = ob_get_contents();  
            @ob_end_clean();  
            if(!$_html_file||(@filesize($_ci_html_path)!=strlen($buffer))){ //如果文件不存在或文件已更变   
                $_html_file=@fopen($_ci_html_path,'w');  
                flock($_html_file, LOCK_EX);  
                fwrite($_html_file, $buffer);                    
                flock($_html_file, LOCK_UN);  
                fclose($_html_file);  
            }  
            //echo(filesize($_ci_html_path)."-".strlen($buffer));   
            include($_ci_html_path);  
        }  
                            
   ......  
    }    
}  
 
              
class MY_Loader extends CI_Loader {
                  
    public function m_view($view, $vars = array(), $return = FALSE){
        return $this->_m_ci_load(array('_ci_view' => $view, '_ci_vars' => $this->_ci_object_to_array($vars), '_ci_return' => $return));
    }
                  
    protected function _m_ci_load($_ci_data){
          .....
                    
            $_ci_html_file=($_ci_ext==='')? $_ci_view.".html" : $_ci_view;//这,生成静态页面的文件名
                          
            foreach ($this->_ci_view_paths as $_ci_view_file => $cascade){
                if (file_exists($_ci_view_file.$_ci_file)){
                    $_ci_path = $_ci_view_file.$_ci_file;
                    $_ci_html_path=$_ci_view_file.$_ci_html_file;//生成静态页面的路径
                    $file_exists = TRUE;
                    break;
                }
      ......
            }
        }
              
     .......
        //在这
      if(config_item("html")===TRUE){//是否开启生成静态页面
            $_html_file=@fopen($_ci_html_path,'r');//创建.html文件
            $buffer = ob_get_contents();
            @ob_end_clean();
            if(!$_html_file||(@filesize($_ci_html_path)!=strlen($buffer))){ //如果文件不存在或文件已更变
                $_html_file=@fopen($_ci_html_path,'w');
                flock($_html_file, LOCK_EX);
                fwrite($_html_file, $buffer);                  
                flock($_html_file, LOCK_UN);
                fclose($_html_file);
            }
            //echo(filesize($_ci_html_path)."-".strlen($buffer));
            include($_ci_html_path);
        }
                          
   ......
    }  
}调用
 
 
[html]  
$this->load->m_view('login',$datas);  
 
$this->load->m_view('login',$datas);
是否生成HTML文件
 
$config["html"]                =  TRUE;
 
 
 
 
全部代码如下
 
 
[php] 
         
class MY_Loader extends CI_Loader {  
             
    public function m_view($view, $vars = array(), $return = FALSE){  
        return $this->_m_ci_load(array('_ci_view' => $view, '_ci_vars' => $this->_ci_object_to_array($vars), '_ci_return' => $return));  
    }  
             
    protected function _m_ci_load($_ci_data){  
        // Set the default data variables   
        foreach (array('_ci_view', '_ci_vars', '_ci_path', '_ci_return') as $_ci_val){  
            $$_ci_val = isset($_ci_data[$_ci_val]) ? $_ci_data[$_ci_val] : FALSE;  
        }  
         
        $file_exists = FALSE;  
        // Set the path to the requested file   
        if (is_string($_ci_path) && $_ci_path !== ''){  
            $_ci_x = explode('/', $_ci_path);//使用一个字符串分割另一个字符串   
            $_ci_file = end($_ci_x);//将数组的内部指针指向最后一个单元   
        }else{  
            $_ci_ext = pathinfo($_ci_view, PATHINFO_EXTENSION);// 返回文件路径的信息   
            $_ci_file = ($_ci_ext === '') ? $_ci_view.'.php' : $_ci_view;  
            $_ci_html_file=($_ci_ext==='')? $_ci_view.".html" : $_ci_view;//这,生成静态页面的文件名   
                     
            foreach ($this->_ci_view_paths as $_ci_view_file => $cascade){  
                if (file_exists($_ci_view_file.$_ci_file)){  
                    $_ci_path = $_ci_view_file.$_ci_file;  
                    $_ci_html_path=$_ci_view_file.$_ci_html_file;//生成静态页面的路径   
                    $file_exists = TRUE;  
                    break;  
                }  
         
                if ( ! $cascade){  
                    break;  
                }  
            }  
        }  
         
        if ( ! $file_exists && ! file_exists($_ci_path))  
        {  
            show_error('Unable to load the requested file: '.$_ci_file);  
        }  
         
        // This allows anything loaded using $this->load (views, files, etc.)   
        // to become accessible from within the Controller and Model functions.   
        $_ci_CI =& get_instance();  
        foreach (get_object_vars($_ci_CI) as $_ci_key => $_ci_var)  
        {  
            if ( ! isset($this->$_ci_key))  
            {  
                $this->$_ci_key =& $_ci_CI->$_ci_key;  
            }  
        }  
         
        /* 
         * Extract and cache variables 
         * 
         * You can either set variables using the dedicated $this->load->vars() 
         * function or via the second parameter of this function. We'll merge 
         * the two types and cache them so that views that are embedded within 
         * other views can have access to these variables. 
         */  
        if (is_array($_ci_vars))  
        {  
            $this->_ci_cached_vars = array_merge($this->_ci_cached_vars, $_ci_vars);  
        }  
        extract($this->_ci_cached_vars);  
         
        /* 
         * Buffer the output 
         * 
         * We buffer the output for two reasons: 
         * 1. Speed. You get a significant speed boost. 
         * 2. So that the final rendered template can be post-processed by 
         *  the output class. Why do we need post processing? For one thing, 
         *  in order to show the elapsed page load time. Unless we can 
         *  intercept the content right before it's sent to the browser and 
         *  then stop the timer it won't be accurate. 
         */  
        ob_start();  
         
        // If the PHP installation does not support short tags we'll   
        // do a little string replacement, changing the short tags   
        // to standard PHP echo statements.   
        if ( ! is_php('5.4') && (bool) @ini_get('short_open_tag') === FALSE  
            && config_item('rewrite_short_tags') === TRUE && function_usable('eval')  
        )  
        {  
            echo eval('?>'.preg_replace('/;*\s*\?>/', '; ?>', str_replace('=', '
        }  
        else  
        {  
            include($_ci_path); // include() vs include_once() allows for multiple views with the same name   
        }  
         
        log_message('debug', 'File loaded: '.$_ci_path);  
         
        // Return the file data if requested   
        if ($_ci_return === TRUE)  
        {  
            $buffer = ob_get_contents();  
            @ob_end_clean();  
            return $buffer;  
        }  
        //在这   
         if(config_item("html")===TRUE){//是否开启生成静态页面   
            $_html_file=@fopen($_ci_html_path,'r');//创建.html文件   
            $buffer = ob_get_contents();  
            @ob_end_clean();  
            if(!$_html_file||(@filesize($_ci_html_path)!=strlen($buffer))){  
                       $_html_file=@fopen($_ci_html_path,'w');  
                       flock($_html_file, LOCK_EX);  
                fwrite($_html_file, $buffer);                    
                flock($_html_file, LOCK_UN);  
                fclose($_html_file);  
            }  
            //echo(filesize($_ci_html_path)."-".strlen($buffer));   
            include($_ci_html_path);  
        }  
                     
         
        /* 
         * Flush the buffer... or buff the flusher? 
         * 
         * In order to permit views to be nested within 
         * other views, we need to flush the content back out whenever 
         * we are beyond the first level of output buffering so that 
         * it can be seen and included properly by the first included 
         * template and any subsequent ones. Oy! 
         */  
        if (ob_get_level() > $this->_ci_ob_level + 1)  
        {  
            ob_end_flush();  
        }  
        else  
        {  
            $_ci_CI->output->append_output(ob_get_contents());  
            @ob_end_clean();  
        }  
    }    
}  
 
       
class MY_Loader extends CI_Loader {
           
    public function m_view($view, $vars = array(), $return = FALSE){
        return $this->_m_ci_load(array('_ci_view' => $view, '_ci_vars' => $this->_ci_object_to_array($vars), '_ci_return' => $return));
    }
           
    protected function _m_ci_load($_ci_data){
        // Set the default data variables
        foreach (array('_ci_view', '_ci_vars', '_ci_path', '_ci_return') as $_ci_val){
            $$_ci_val = isset($_ci_data[$_ci_val]) ? $_ci_data[$_ci_val] : FALSE;
        }
       
        $file_exists = FALSE;
        // Set the path to the requested file
        if (is_string($_ci_path) && $_ci_path !== ''){
            $_ci_x = explode('/', $_ci_path);//使用一个字符串分割另一个字符串
            $_ci_file = end($_ci_x);//将数组的内部指针指向最后一个单元
        }else{
            $_ci_ext = pathinfo($_ci_view, PATHINFO_EXTENSION);// 返回文件路径的信息
            $_ci_file = ($_ci_ext === '') ? $_ci_view.'.php' : $_ci_view;
            $_ci_html_file=($_ci_ext==='')? $_ci_view.".html" : $_ci_view;//这,生成静态页面的文件名
                   
            foreach ($this->_ci_view_paths as $_ci_view_file => $cascade){
                if (file_exists($_ci_view_file.$_ci_file)){
                    $_ci_path = $_ci_view_file.$_ci_file;
                    $_ci_html_path=$_ci_view_file.$_ci_html_file;//生成静态页面的路径
                    $file_exists = TRUE;
                    break;
                }
       
                if ( ! $cascade){
                    break;
                }
            }
        }
       
        if ( ! $file_exists && ! file_exists($_ci_path))
        {
            show_error('Unable to load the requested file: '.$_ci_file);
        }
       
        // This allows anything loaded using $this->load (views, files, etc.)
        // to become accessible from within the Controller and Model functions.
        $_ci_CI =& get_instance();
        foreach (get_object_vars($_ci_CI) as $_ci_key => $_ci_var)
        {
            if ( ! isset($this->$_ci_key))
            {
                $this->$_ci_key =& $_ci_CI->$_ci_key;
            }
        }
       
        /*
         * Extract and cache variables
         *
         * You can either set variables using the dedicated $this->load->vars()
         * function or via the second parameter of this function. We'll merge
         * the two types and cache them so that views that are embedded within
         * other views can have access to these variables.
         */
        if (is_array($_ci_vars))
        {
            $this->_ci_cached_vars = array_merge($this->_ci_cached_vars, $_ci_vars);
        }
        extract($this->_ci_cached_vars);
       
        /*
         * Buffer the output
         *
         * We buffer the output for two reasons:
         * 1. Speed. You get a significant speed boost.
         * 2. So that the final rendered template can be post-processed by
         *  the output class. Why do we need post processing? For one thing,
         *  in order to show the elapsed page load time. Unless we can
         *  intercept the content right before it's sent to the browser and
         *  then stop the timer it won't be accurate.
         */
        ob_start();
       
        // If the PHP installation does not support short tags we'll
        // do a little string replacement, changing the short tags
        // to standard PHP echo statements.
        if ( ! is_php('5.4') && (bool) @ini_get('short_open_tag') === FALSE
            && config_item('rewrite_short_tags') === TRUE && function_usable('eval')
        )
        {
            echo eval('?>'.preg_replace('/;*\s*\?>/', '; ?>', str_replace('=', '
        }
        else
        {
            include($_ci_path); // include() vs include_once() allows for multiple views with the same name
        }
       
        log_message('debug', 'File loaded: '.$_ci_path);
       
        // Return the file data if requested
        if ($_ci_return === TRUE)
        {
            $buffer = ob_get_contents();
            @ob_end_clean();
            return $buffer;
        }
        //在这
         if(config_item("html")===TRUE){//是否开启生成静态页面
            $_html_file=@fopen($_ci_html_path,'r');//创建.html文件
            $buffer = ob_get_contents();
            @ob_end_clean();
            if(!$_html_file||(@filesize($_ci_html_path)!=strlen($buffer))){
                       $_html_file=@fopen($_ci_html_path,'w');
                       flock($_html_file, LOCK_EX);
                fwrite($_html_file, $buffer);                  
                flock($_html_file, LOCK_UN);
                fclose($_html_file);
            }
            //echo(filesize($_ci_html_path)."-".strlen($buffer));
            include($_ci_html_path);
        }
                   
       
        /*
         * Flush the buffer... or buff the flusher?
         *
         * In order to permit views to be nested within
         * other views, we need to flush the content back out whenever
         * we are beyond the first level of output buffering so that
         * it can be seen and included properly by the first included
         * template and any subsequent ones. Oy!
         */ www.2cto.com
        if (ob_get_level() > $this->_ci_ob_level + 1)
        {
            ob_end_flush();
        }
        else
        {
            $_ci_CI->output->append_output(ob_get_contents());
            @ob_end_clean();
        }
    }  
}
 

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/477728.htmlTechArticle使用CI来生成静态页面,其实很简单,就像论坛里面说的那样,读出页面中的数据,再写入html文件中,最后显示这个html文件就行了,好吧,上码。...
성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
로드 밸런싱이 세션 관리에 어떤 영향을 미치는지 설명하고 해결 방법을 설명하십시오.로드 밸런싱이 세션 관리에 어떤 영향을 미치는지 설명하고 해결 방법을 설명하십시오.Apr 29, 2025 am 12:42 AM

로드 밸런싱은 세션 관리에 영향을 미치지 만 세션 복제, 세션 끈적임 및 중앙 집중식 세션 스토리지로 해결할 수 있습니다. 1. 세션 복제 복사 서버 간의 세션 데이터. 2. 세션 끈은 사용자 요청을 동일한 서버로 안내합니다. 3. 중앙 집중식 세션 스토리지는 Redis와 같은 독립 서버를 사용하여 세션 데이터를 저장하여 데이터 공유를 보장합니다.

세션 잠금의 개념을 설명하십시오.세션 잠금의 개념을 설명하십시오.Apr 29, 2025 am 12:39 AM

SessionLockingIsateChniqueSureDureauser의 SessionLockingSsessionRemainSexclusivetoOneuseratatime.itiscrucialforpreptingdatacorruptionandsecurityBreachesInmulti-userApplications.sessionLockingSogingSompletEdusingserVerver-sidelockingMegynisms, unrasprantlockinj

PHP 세션에 대한 대안이 있습니까?PHP 세션에 대한 대안이 있습니까?Apr 29, 2025 am 12:36 AM

PHP 세션의 대안에는 쿠키, 토큰 기반 인증, 데이터베이스 기반 세션 및 Redis/Memcached가 포함됩니다. 1. Cookies는 클라이언트에 데이터를 저장하여 세션을 관리합니다. 이는 단순하지만 보안이 적습니다. 2. Token 기반 인증은 토큰을 사용하여 사용자를 확인합니다. 이는 매우 안전하지만 추가 논리가 필요합니다. 3. Database 기반 세션은 데이터베이스에 데이터를 저장하여 확장 성이 좋지만 성능에 영향을 줄 수 있습니다. 4. Redis/Memcached는 분산 캐시를 사용하여 성능 및 확장 성을 향상하지만 추가 일치가 필요합니다.

PHP의 맥락에서 '세션 납치'라는 용어를 정의하십시오.PHP의 맥락에서 '세션 납치'라는 용어를 정의하십시오.Apr 29, 2025 am 12:33 AM

SessionHijacking은 사용자의 SessionID를 얻음으로써 사용자를 가장하는 공격자를 말합니다. 예방 방법은 다음과 같습니다. 1) HTTPS를 사용한 의사 소통 암호화; 2) SessionID의 출처를 확인; 3) 보안 세션 생성 알고리즘 사용; 4) 정기적으로 SessionID를 업데이트합니다.

PHP의 전체 형태는 무엇입니까?PHP의 전체 형태는 무엇입니까?Apr 28, 2025 pm 04:58 PM

이 기사는 PHP에 대해 설명하고, 전체 형식, 웹 개발의 주요 용도, Python 및 Java와의 비교 및 ​​초보자를위한 학습 용이성을 자세히 설명합니다.

PHP는 양식 데이터를 어떻게 처리합니까?PHP는 양식 데이터를 어떻게 처리합니까?Apr 28, 2025 pm 04:57 PM

PHP는 유효성 검사, 소독 및 보안 데이터베이스 상호 작용을 통해 보안을 보장하면서 $ \ _ post 및 $ \ _를 사용하여 데이터 양식 데이터를 처리합니다.

PHP와 ASP.NET의 차이점은 무엇입니까?PHP와 ASP.NET의 차이점은 무엇입니까?Apr 28, 2025 pm 04:56 PM

이 기사는 PHP와 ASP.NET을 비교하여 대규모 웹 응용 프로그램, 성능 차이 및 보안 기능에 대한 적합성에 중점을 둡니다. 둘 다 대규모 프로젝트에서는 실용적이지만 PHP는 오픈 소스 및 플랫폼 독립적이며 ASP.NET,

PHP는 사례에 민감한 언어입니까?PHP는 사례에 민감한 언어입니까?Apr 28, 2025 pm 04:55 PM

PHP의 사례 감도는 다양합니다. 함수는 무감각하고 변수와 클래스는 민감합니다. 모범 사례에는 일관된 이름 지정 및 비교를위한 사례 감수 기능 사용이 포함됩니다.

See all articles

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

Video Face Swap

Video Face Swap

완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

뜨거운 도구

mPDF

mPDF

mPDF는 UTF-8로 인코딩된 HTML에서 PDF 파일을 생성할 수 있는 PHP 라이브러리입니다. 원저자인 Ian Back은 자신의 웹 사이트에서 "즉시" PDF 파일을 출력하고 다양한 언어를 처리하기 위해 mPDF를 작성했습니다. HTML2FPDF와 같은 원본 스크립트보다 유니코드 글꼴을 사용할 때 속도가 느리고 더 큰 파일을 생성하지만 CSS 스타일 등을 지원하고 많은 개선 사항이 있습니다. RTL(아랍어, 히브리어), CJK(중국어, 일본어, 한국어)를 포함한 거의 모든 언어를 지원합니다. 중첩된 블록 수준 요소(예: P, DIV)를 지원합니다.

안전한 시험 브라우저

안전한 시험 브라우저

안전한 시험 브라우저는 온라인 시험을 안전하게 치르기 위한 보안 브라우저 환경입니다. 이 소프트웨어는 모든 컴퓨터를 안전한 워크스테이션으로 바꿔줍니다. 이는 모든 유틸리티에 대한 액세스를 제어하고 학생들이 승인되지 않은 리소스를 사용하는 것을 방지합니다.

SublimeText3 Mac 버전

SublimeText3 Mac 버전

신 수준의 코드 편집 소프트웨어(SublimeText3)

SecList

SecList

SecLists는 최고의 보안 테스터의 동반자입니다. 보안 평가 시 자주 사용되는 다양한 유형의 목록을 한 곳에 모아 놓은 것입니다. SecLists는 보안 테스터에게 필요할 수 있는 모든 목록을 편리하게 제공하여 보안 테스트를 더욱 효율적이고 생산적으로 만드는 데 도움이 됩니다. 목록 유형에는 사용자 이름, 비밀번호, URL, 퍼징 페이로드, 민감한 데이터 패턴, 웹 셸 등이 포함됩니다. 테스터는 이 저장소를 새로운 테스트 시스템으로 간단히 가져올 수 있으며 필요한 모든 유형의 목록에 액세스할 수 있습니다.

Eclipse용 SAP NetWeaver 서버 어댑터

Eclipse용 SAP NetWeaver 서버 어댑터

Eclipse를 SAP NetWeaver 애플리케이션 서버와 통합합니다.