如何縮小php頁面html輸出?

[英]How to minify php page html output?


I am looking for a php script or class that can minify my php page html output like google page speed does.

我正在尋找一個php腳本或類,可以縮小我的php頁面html輸出,如谷歌頁面速度。

How can I do this?

我該怎么做呢?

13 个解决方案

#1


159  

CSS and Javascript

Consider the following link to minify Javascript/CSS files: https://github.com/mrclay/minify

考慮以下鏈接來縮小Javascript/CSS文件:https://github.com/mrclay/minify

HTML

Tell Apache to deliver HTML with GZip - this generally reduces the response size by about 70%. (If you use Apache, the module configuring gzip depends on your version: Apache 1.3 uses mod_gzip while Apache 2.x uses mod_deflate.)

告訴Apache使用GZip交付HTML——這通常會減少70%的響應大小。(如果使用Apache,配置gzip的模塊取決於您的版本:Apache 1.3使用mod_gzip而Apache 2使用。x使用mod_deflate。)

Accept-Encoding: gzip, deflate

接受編碼:gzip壓縮

Content-Encoding: gzip

內容編碼:gzip

Use the following snippet to remove white-spaces from the HTML with the help ob_start's buffer:

使用以下代碼片段從幫助ob_start的緩沖區中刪除空白:

<?php

function sanitize_output($buffer) {

    $search = array(
        '/\>[^\S ]+/s',     // strip whitespaces after tags, except space
        '/[^\S ]+\</s',     // strip whitespaces before tags, except space
        '/(\s)+/s',         // shorten multiple whitespace sequences
        '/<!--(.|\s)*?-->/' // Remove HTML comments
    );

    $replace = array(
        '>',
        '<',
        '\\1',
        ''
    );

    $buffer = preg_replace($search, $replace, $buffer);

    return $buffer;
}

ob_start("sanitize_output");

?>

#2


23  

Turn on gzip if you want to do it properly. You can also just do something like this:

打開gzip,如果你想做得正確。你也可以這樣做:

$this->output = preg_replace(
    array(
        '/ {2,}/',
        '/<!--.*?-->|\t|(?:\r?\n[ \t]*)+/s'
    ),
    array(
        ' ',
        ''
    ),
    $this->output
);

This removes about 30% of the page size by turning your html into one line, no tabs, no new lines, no comments. Mileage may vary

通過將html轉換為一行、無制表符、無新行、無注釋,可以刪除大約30%的頁面大小。實際情況可能會發生變化

#3


17  

All of the preg_replace() solutions above have issues of single line comments, conditional comments and other pitfalls. I'd recommend taking advantage of the well-tested Minify project rather than creating your own regex from scratch.

上面所有的preg_replace()解決方案都存在單行注釋、條件注釋和其他缺陷的問題。我建議利用測試良好的Minify項目,而不是從頭創建自己的regex。

In my case I place the following code at the top of a PHP page to minify it:

在我的例子中,我將下面的代碼放在PHP頁面的頂部,以縮小它:

function sanitize_output($buffer) {
    require_once('min/lib/Minify/HTML.php');
    require_once('min/lib/Minify/CSS.php');
    require_once('min/lib/JSMin.php');
    $buffer = Minify_HTML::minify($buffer, array(
        'cssMinifier' => array('Minify_CSS', 'minify'),
        'jsMinifier' => array('JSMin', 'minify')
    ));
    return $buffer;
}
ob_start('sanitize_output');

#4


14  

I've tried several minifiers and they either remove too little or too much.

我試過幾款小巧的,但它們要么刪除得太少,要么刪除得太多。

This code removes redundant empty spaces and optional HTML (ending) tags. Also it plays it safe and does not remove anything that could potentially break HTML, JS or CSS.

此代碼刪除冗余空空間和可選的HTML(結束)標記。它也很安全,不會刪除任何可能破壞HTML、JS或CSS的內容。

Also the code shows how to do that in Zend Framework:

代碼還展示了如何在Zend框架中實現這一點:

class Application_Plugin_Minify extends Zend_Controller_Plugin_Abstract {

  public function dispatchLoopShutdown() {
    $response = $this->getResponse();
    $body = $response->getBody(); //actually returns both HEAD and BODY

    //remove redundant (white-space) characters
    $replace = array(
        //remove tabs before and after HTML tags
        '/\>[^\S ]+/s'   => '>',
        '/[^\S ]+\</s'   => '<',
        //shorten multiple whitespace sequences; keep new-line characters because they matter in JS!!!
        '/([\t ])+/s'  => ' ',
        //remove leading and trailing spaces
        '/^([\t ])+/m' => '',
        '/([\t ])+$/m' => '',
        // remove JS line comments (simple only); do NOT remove lines containing URL (e.g. 'src="http://server.com/"')!!!
        '~//[a-zA-Z0-9 ]+$~m' => '',
        //remove empty lines (sequence of line-end and white-space characters)
        '/[\r\n]+([\t ]?[\r\n]+)+/s'  => "\n",
        //remove empty lines (between HTML tags); cannot remove just any line-end characters because in inline JS they can matter!
        '/\>[\r\n\t ]+\</s'    => '><',
        //remove "empty" lines containing only JS's block end character; join with next line (e.g. "}\n}\n</script>" --> "}}</script>"
        '/}[\r\n\t ]+/s'  => '}',
        '/}[\r\n\t ]+,[\r\n\t ]+/s'  => '},',
        //remove new-line after JS's function or condition start; join with next line
        '/\)[\r\n\t ]?{[\r\n\t ]+/s'  => '){',
        '/,[\r\n\t ]?{[\r\n\t ]+/s'  => ',{',
        //remove new-line after JS's line end (only most obvious and safe cases)
        '/\),[\r\n\t ]+/s'  => '),',
        //remove quotes from HTML attributes that does not contain spaces; keep quotes around URLs!
        '~([\r\n\t ])?([a-zA-Z0-9]+)="([a-zA-Z0-9_/\\-]+)"([\r\n\t ])?~s' => '$1$2=$3$4', //$1 and $4 insert first white-space character found before/after attribute
    );
    $body = preg_replace(array_keys($replace), array_values($replace), $body);

    //remove optional ending tags (see http://www.w3.org/TR/html5/syntax.html#syntax-tag-omission )
    $remove = array(
        '</option>', '</li>', '</dt>', '</dd>', '</tr>', '</th>', '</td>'
    );
    $body = str_ireplace($remove, '', $body);

    $response->setBody($body);
  }
}

But note that when using gZip compression your code gets compressed a lot more that any minification can do so combining minification and gZip is pointless, because time saved by downloading is lost by minification and also saves minimum.

但是請注意,當使用gZip壓縮時,您的代碼會被壓縮得更多,而任何迷你化都可以做到這一點,將迷你化和gZip結合在一起是沒有意義的,因為下載節省的時間會因為迷你化而丟失,同時也會節省最少的時間。

Here are my results (download via 3G network):

以下是我的結果(通過3G網絡下載):

 Original HTML:        150kB       180ms download
 gZipped HTML:          24kB        40ms
 minified HTML:        120kB       150ms download + 150ms minification
 min+gzip HTML:         22kB        30ms download + 150ms minification

#5


3  

you can check out this set of classes: https://code.google.com/p/minify/source/browse/?name=master#git%2Fmin%2Flib%2FMinify , you'll find html/css/js minification classes there.

您可以查看這組類:https://code.google.com/p/minify/source/browse/?名稱=master#git%2Fmin%2Flib%2FMinify,您可以在那里找到html/css/js迷你類。

you can also try this: http://code.google.com/p/htmlcompressor/

您也可以嘗試:http://code.google.com/p/htmlcompressor/

Good luck :)

祝你好運:)

#6


3  

Create a PHP file outside your document root. If your document root is

在文檔根之外創建一個PHP文件。如果您的文檔根目錄是

/var/www/html/

create the a file named minify.php one level above it

創建一個名為minify的文件。php比它高一級

/var/www/minify.php

Copy paste the following PHP code into it

復制粘貼以下PHP代碼到其中

<?php
function minify_output($buffer){
    $search = array('/\>[^\S ]+/s','/[^\S ]+\</s','/(\s)+/s');
    $replace = array('>','<','\\1');
    if (preg_match("/\<html/i",$buffer) == 1 && preg_match("/\<\/html\>/i",$buffer) == 1) {
        $buffer = preg_replace($search, $replace, $buffer);
    }
    return $buffer;
}
ob_start("minify_output");?>

Save the minify.php file and open the php.ini file. If it is a dedicated server/VPS search for the following option, on shared hosting with custom php.ini add it.

保存貶低。打開php文件。ini文件。如果是一個專用的服務器/VPS搜索,可以使用自定義php共享主機。ini添加它。

auto_prepend_file = /var/www/minify.php

Reference: http://websistent.com/how-to-use-php-to-minify-html-output/

參考:http://websistent.com/how-to-use-php-to-minify-html-output/

#7


2  

You can look into HTML TIDY - http://uk.php.net/tidy

您可以查看HTML TIDY - http://uk.php.net/tidy

It can be installed as a PHP module and will (correctly, safely) strip whitespace and all other nastiness, whilst still outputting perfectly valid HTML / XHTML markup. It will also clean your code, which can be a great thing or a terrible thing, depending on how good you are at writing valid code in the first place ;-)

它可以作為PHP模塊安裝,並將(正確、安全地)刪除空格和所有其他糟糕的內容,同時仍然輸出完全有效的HTML / XHTML標記。它還將清理您的代碼,這可能是一件好事,也可能是一件糟糕的事情,這取決於您在編寫有效代碼時的水平;

Additionally, you can gzip the output using the following code at the start of your file:

此外,您可以在文件開頭使用以下代碼gzip輸出:

ob_start('ob_gzhandler');

#8


2  

First of all gzip can help you more than a Html Minifier

首先,gzip可以幫助您超過一個Html縮小者。

  1. With nginx:

    nginx:

    gzip on;
    gzip_disable "msie6";
    
    gzip_vary on;
    gzip_proxied any;
    gzip_comp_level 6;
    gzip_buffers 16 8k;
    gzip_http_version 1.1;
    gzip_types text/plain text/css application/json application/x-javascript text/xml application/xml application/xml+rss text/javascript;
    
  2. With apache you can use mod_gzip
  3. 使用apache,您可以使用mod_gzip

Second: with gzip + Html Minification you can reduce the file size drastically!!!

第二:使用gzip + Html迷你化,你可以大幅減少文件大小!!!

I've created this HtmlMinifier for PHP.

我已經為PHP創建了這個HtmlMinifier。

You can retrieve it through composer: composer require arjanschouten/htmlminifier dev-master.

您可以通過composer: composer需要arjanschouten/htmlminifier dev-master來檢索它。

There is a Laravel service provider. If you're not using Laravel you can use it from PHP.

這里有一個大型的服務提供商。如果不使用Laravel,可以從PHP中使用它。

// create a minify context which will be used through the minification process
$context = new MinifyContext(new PlaceholderContainer());
// save the html contents in the context
$context->setContents('<html>My html...</html>');
$minify = new Minify();
// start the process and give the context with it as parameter
$context = $minify->run($context);

// $context now contains the minified version
$minifiedContents = $context->getContents();

As you can see you can extend a lot of things in here and you can pass various options. Check the readme to see all the available options.

如您所見,您可以在這里擴展許多內容,並傳遞各種選項。檢查readme以查看所有可用的選項。

This HtmlMinifier is complete and safe. It takes 3 steps for the minification process:

這個HtmlMinifier是完整和安全的。縮小過程需要三個步驟:

  1. Replace critical content temporary with a placeholder.
  2. 用占位符替換臨時的關鍵內容。
  3. Run the minification strategies.
  4. 運行縮小策略。
  5. Restore the original content.
  6. 恢復原來的內容。

I would suggest that you cache the output of you're views. The minification process should be a one time process. Or do it for example interval based.

我建議您緩存視圖的輸出。縮小過程應該是一個一次性的過程。或者以區間為例。

Clear benchmarks are not created at the time. However the minifier can reduce the page size with 5-25% based on the your markup!

沒有創建明確的基准。然而,縮小器可以根據您的標記減少5-25%的頁面大小!

If you want to add you're own strategies you can use the addPlaceholder and the addMinifier methods.

如果想添加自己的策略,可以使用addPlaceholder和addMinifier方法。

#9


2  

I have a GitHub gist contains PHP functions to minify HTML, CSS and JS files → https://gist.github.com/tovic/d7b310dea3b33e4732c0

我有一個GitHub要點包含PHP函數來貶低HTML、CSS和javascript文件→https://gist.github.com/tovic/d7b310dea3b33e4732c0

Here’s how to minify the HTML output on the fly with output buffer:

以下是如何使用輸出緩沖區動態地縮小HTML輸出:

<?php

include 'path/to/php-html-css-js-minifier.php';

ob_start('minify_html');

?>

<!-- HTML code goes here ... -->

<?php echo ob_get_clean(); ?>

#10


2  

This work for me.

這項工作對我來說。

function Minify_Html($Html)
{
   $Search = array(
    '/(\n|^)(\x20+|\t)/',
    '/(\n|^)\/\/(.*?)(\n|$)/',
    '/\n/',
    '/\<\!--.*?-->/',
    '/(\x20+|\t)/', # Delete multispace (Without \n)
    '/\>\s+\</', # strip whitespaces between tags
    '/(\"|\')\s+\>/', # strip whitespaces between quotation ("') and end tags
    '/=\s+(\"|\')/'); # strip whitespaces between = "'

   $Replace = array(
    "\n",
    "\n",
    " ",
    "",
    " ",
    "><",
    "$1>",
    "=$1");

$Html = preg_replace($Search,$Replace,$Html);
return $Html;
}

#11


1  

If you want to remove all new lines in the page, use this fast code:

如果您想刪除頁面中的所有新行,請使用以下快速代碼:

ob_start(function($b){
if(strpos($b, "<html")!==false) {
return str_replace(PHP_EOL,"",$b);
} else {return $b;}
});

#12


0  

Thanks to Andrew. Here's what a did to use this in cakePHP:

多虧了安德魯。下面是a在cakePHP中使用的方法:

  1. Download minify-2.1.7
  2. 下載minify-2.1.7
  3. Unpack the file and copy min subfolder to cake's Vendor folder
  4. 打開文件並將min子文件夾復制到cake的供應商文件夾
  5. Creates MinifyCodeHelper.php in cake's View/Helper like this:

    創建MinifyCodeHelper。php在cake的視圖/幫助器如下:

    App::import('Vendor/min/lib/Minify/', 'HTML');
    App::import('Vendor/min/lib/Minify/', 'CommentPreserver');
    App::import('Vendor/min/lib/Minify/CSS/', 'Compressor');
    App::import('Vendor/min/lib/Minify/', 'CSS');
    App::import('Vendor/min/lib/', 'JSMin');
    class MinifyCodeHelper extends Helper {
        public function afterRenderFile($file, $data) {
            if( Configure::read('debug') < 1 ) //works only e production mode
                $data = Minify_HTML::minify($data, array(
                    'cssMinifier' => array('Minify_CSS', 'minify'),
                    'jsMinifier' => array('JSMin', 'minify')
                ));
            return $data;
        }
    }
    
  6. Enabled my Helper in AppController

    在AppController中啟用助手

    public $helpers = array ('Html','...','MinifyCode');

    公共$助手=陣列(“Html”、“…”,“MinifyCode”);

5... Voila!

5……瞧!

My conclusion: If apache's deflate and headers modules is disabled in your server your gain is 21% less size and 0.35s plus in request to compress (this numbers was in my case).

我的結論是:如果在服務器中禁用了apache的deflate和header模塊,那么在請求壓縮時,您的增益將減少21%和0.35秒(在我的例子中是這個數字)。

But if you had enable apache's modules the compressed response has no significant difference (1.3% to me) and the time to compress is the samne (0.3s to me).

但是,如果您啟用了apache的模塊,壓縮響應就沒有顯著的差異(我認為是1.3%),壓縮的時間是samne(我認為是0.3秒)。

So... why did I do that? 'couse my project's doc is all in comments (php, css and js) and my final user dont need to see this ;)

所以…我為什么要這么做?“但我的項目的doc都有注釋(php、css和js),我的最終用戶不需要看這個;”

#13


0  

You can use a well tested Java minifier like HTMLCompressor by invoking it using passthru (exec).
Remember to redirect console using 2>&1

通過使用passthru (exec)調用,您可以使用經過良好測試的Java縮小程序,如html壓縮機。記住使用2>和1重定向控制台

This however may not be useful, if speed is a concern. I use it for static php output

然而,如果考慮到速度的話,這可能並不有用。我將它用於靜態php輸出


注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2011/06/03/323789a141d98e1aabe0d0009529ccff.html



 
  © 2014-2022 ITdaan.com 联系我们: