如何缩小php页面的html输出?

时间:2011-06-03 09:36:07

标签: php html minify

我正在寻找一个可以缩小我的php页面html输出的php脚本或类,就像google page speed一样。

我该怎么做?

13 个答案:

答案 0 :(得分:192)

CSS和Javascript

考虑以下链接来缩小Javascript / CSS文件:https://github.com/mrclay/minify

HTML

告诉Apache使用GZip传递HTML - 这通常会使响应大小减少约70%。 (如果你使用Apache,配置gzip的模块取决于你的版本:Apache 1.3使用mod_gzip,而Apache 2.x使用mod_deflate。)

  

Accept-Encoding:gzip,deflate

     

内容编码:gzip

使用following snippet使用帮助ob_start的缓冲区从HTML中删除空格:

<?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");

?>

答案 1 :(得分:26)

如果要正确执行此操作,请启用gzip。你也可以这样做:

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

通过将html变为一行,没有标签,没有新行,没有评论,这可以消除大约30%的页面大小。里程可能会有所不同

答案 2 :(得分:17)

上述所有preg_replace()解决方案都存在单行注释,条件注释和其他陷阱问题。我建议利用经过充分测试的Minify project,而不是从头开始创建自己的正则表达式。

在我的情况下,我将以下代码放在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');

答案 3 :(得分:16)

我尝试了几种缩放器,它们要么移得太少,要么移得太多。

此代码删除多余的空白空间和可选的HTML(结束)标记。此外,它可以安全地播放,也不会删除任何可能破坏HTML,JS或CSS的内容。

该代码还显示了如何在Zend Framework中执行此操作:

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);
  }
}

但是请注意,当使用gZip压缩时,你的代码会被压缩得更多,任何缩小都可以做到这一点,因此结合缩小和gZip是没有意义的,因为下载所节省的时间会因缩小而丢失,并且还可以节省最少的时间。

以下是我的结果(通过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

答案 4 :(得分:5)

这项工作适合我。

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;
}

答案 5 :(得分:4)

  

在文档根目录之外创建一个PHP文件。如果您的文档根目录是

/var/www/html/
     

在其上方创建一个名为minify.php的文件

/var/www/minify.php
     

将以下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");?>
     

保存minify.php文件并打开php.ini文件。如果是专用服务器/ VPS搜索以下选项,则在使用自定义php.ini的共享主机上添加它。

auto_prepend_file = /var/www/minify.php

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

答案 6 :(得分:3)

你可以查看这组课程: https://code.google.com/p/minify/source/browse/?name=master#git%2Fmin%2Flib%2FMinify,你会在那里找到html / css / js缩小课程。

你也可以试试这个:http://code.google.com/p/htmlcompressor/

祝你好运:)

答案 7 :(得分:2)

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

它可以作为PHP模块安装,并且(正确,安全地)去除空白和所有其他恶意,同时仍然输出完全有效的HTML / XHTML标记。它也会清理你的代码,这可能是一件好事或一件可怕的事情,这取决于你在编写有效代码方面的优势; - )

此外,您可以使用文件开头的以下代码对输出进行gzip:

ob_start('ob_gzhandler');

答案 8 :(得分:2)

首先,gzip可以帮助你的不仅仅是一个Html Minifier

  1. With 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. 第二:使用gzip + Html Minification可以大幅减少文件大小!!!

    我已经创建了这个HtmlMinifier for PHP

    您可以通过作曲家检索它:composer require arjanschouten/htmlminifier dev-master

    有一个Laravel服务提供商。如果你不使用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();
    

    正如你所看到的,你可以在这里扩展很多东西,你可以通过各种选择。 Check the readme查看所有可用选项。

    HtmlMinifier完整且安全。缩小过程需要3个步骤:

    1. 使用占位符替换临时关键内容。
    2. 运行缩小策略。
    3. 恢复原始内容。
    4. 我建议您缓存视图的输出。缩小过程应该是一次性过程。或者以例如基于区间为基础进行。

      当时没有创建明确的基准。但是,根据您的标记,缩小器可以将页面大小减少5-25%!

      如果您想添加自己的策略,可以使用addPlaceholderaddMinifier方法。

答案 9 :(得分:2)

我有一个 GitHub 要点包含PHP函数来缩小HTML,CSS和JS文件→https://gist.github.com/tovic/d7b310dea3b33e4732c0

以下是如何使用输出缓冲区动态缩小HTML输出:

for

答案 10 :(得分:1)

如果要删除页面中的所有新行,请使用以下快速代码:

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

答案 11 :(得分:0)

感谢Andrew。 这是在cakePHP中使用它的原因:

  1. 下载minify-2.1.7
  2. 解压缩文件并将min子文件夹复制到cake的供应商文件夹
  3. 在cake的View / Helper中创建MinifyCodeHelper.php,如下所示:

    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;
        }
    }
    
  4. 在AppController中启用了我的助手

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

  5. 5 ......瞧!

    我的结论:如果你的服务器禁用了apache的deflate和headers模块,你的增益大小减少21%,压缩请求增加0.35s(这个数字在我的情况下)。

    但是如果你启用了apache的模块,压缩响应没有显着差异(对我来说是1.3%),压缩时间是samne(对我来说是0.3s)。

    那么......为什么我这样做? '我的项目的文档都在评论中(php,css和js),我的最终用户不需要看到这个;)

答案 12 :(得分:0)

您可以使用passthruexec)调用经过严格测试的Java缩略器,例如HTMLCompressor。 请记住使用2>&1

重定向控制台

如果速度是一个问题,这可能没有用。我用它来静态php输出