如何缩小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 联系我们: