PHP-CI – 壓縮輸出網頁原始碼
https://php.quicoto.com/how-to-speed-up-codeigniter/
他原本的用意是想加快網頁輸出速度,將一堆不必要的空白、斷行,全部都濃縮成一行輸出,
使用的是PHP CodeIgniter,
第一步,先在application/config/config.php 將 enable_hooks開啟
$config['enable_hooks'] = TRUE;
第二步,application/config/hooks.php 撰寫以下程式碼
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
/*
| -------------------------------------------------------------------------
| Hooks
| -------------------------------------------------------------------------
| This file lets you define "hooks" to extend CI without hacking the core
| files. Please see the user guide for info:
|
| https://codeigniter.com/user_guide/general/hooks.html
|
*/
$hook['display_override'][] = array(
'class' => '',
'function' => 'compress',
'filename' => 'compress.php',
'filepath' => 'hooks'
);
?>
第三步,在application/hooks資料夾底下,建立compress.php
<?php
$CI =& get_instance();
$buffer = $CI->output->get_output();
$search = array(
'/\>[^\S ]+/s',
'/[^\S ]+\</s',
'/(\s)+/s', // shorten multiple whitespace sequences
'#(?://)?<!\[CDATA\[(.*?)(?://)?\]\]>#s' //leave CDATA alone
);
$replace = array(
'>',
'<',
'\\1',
"//<![CDATA[\n".'\1'."\n//]]>"
);
$buffer = preg_replace($search, $replace, $buffer);
$CI->output->set_output($buffer);
$CI->output->_display();
?>
這三步做完,就可以完成如下這樣亂七八糟的原始碼輸出
<!DOCTYPE html><html lang="zh-Hant-TW"><head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Tom Lai Tools</title> <!-- Bootstrap --> <link
文章則有如何做Cache(如果有些資料非常頻繁使用的話)
可以使用
$this->output->cache(60);
及如何開啟Gzip輸出(但這個用了之後,我大概程式碼都不能輸出)
$config[‘compress_output’] = TRUE;