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

m3t*_*sys 136 html php minify

我正在寻找一个PHP脚本或类,可以缩小我的PHP页面html输出像谷歌页面速度.

我怎样才能做到这一点?

Rak*_*kar 202

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

使用以下代码段使用帮助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");

?>
Run Code Online (Sandbox Code Playgroud)

  • 这是一个很好的功能,但如果你使用**PRE**标签,请注意它,有时会删除换行符. (53认同)
  • 这也打破了内联JavaScript(即在`<script>`标签中),它们在每个语句的末尾都没有`;`或者有使用`//`的注释 (19认同)
  • 您还可以使用Minify库中的Minify_HTML类(`$ content =\Minify_HTML :: minify($ content);`,您甚至可以为内联代码添加回调到js/css minifiers).请参阅https://github.com/mrclay/minify/blob/master/min/lib/Minify/HTML.php (8认同)
  • 这将删除textarea,pre,input,img中的空格,这也打破了内联javascripts.如果有人不乐意使用基于regexp的DOM解析[this solution](https://gist.github.com/tovic/d7b310dea3b33e4732c0)的庞大类很有效 (7认同)
  • 这段代码应该放在脚本的顶部还是底部? (2认同)

dog*_*c69 27

如果要正确执行,请打开gzip.你也可以这样做:

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

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

  • 这可能是有潜在危险的,因为它也会删除IE条件...... - 你需要将它更改为/< !--(?!〜[if).*? - > / (18认同)
  • 不起作用,删除太多,搞乱代码.在W3C有效之前,之后不是. (3认同)
  • 不幸的是,它也打破了Javascript代码,比如生成更复杂的Google地图实现 - 这正是我需要这样的功能. (3认同)

And*_*rew 19

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

在我的例子中,我将以下代码放在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');
Run Code Online (Sandbox Code Playgroud)

  • 您的代码不会将 html 放入一行 (2认同)

Rad*_*ech 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);
  }
}
Run Code Online (Sandbox Code Playgroud)

但请注意,当使用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
Run Code Online (Sandbox Code Playgroud)

  • 是的,我同意它看起来毫无意义,但它可以为google获得一两个宝贵的点数,这与你的google排名有关.您的代码非常适合剥离不需要的空间.谢谢 :-) (4认同)

Moh*_*day 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;
}
Run Code Online (Sandbox Code Playgroud)

  • 这删除了已接受的答案未删除的空格。谢谢! (2认同)
  • 我认为最好的答案,这对我来说非常好......谢谢 (2认同)