php 如何缩小php页面html输出?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6225351/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to minify php page html output?
提问by m3tsys
I am looking for a php script or class that can minify my php page html output like google page speed does.
我正在寻找一个可以像谷歌页面速度一样缩小我的 php 页面 html 输出的 php 脚本或类。
How can I do this?
我怎样才能做到这一点?
回答by Rakesh Sankar
CSS and Javascript
CSS 和 JavaScript
Consider the following link to minify Javascript/CSS files: https://github.com/mrclay/minify
考虑使用以下链接来缩小 Javascript/CSS 文件:https: //github.com/mrclay/minify
HTML
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
Content-Encoding: gzip
接受编码:gzip、deflate
内容编码:gzip
Use the following snippetto remove white-spaces from the HTML with the help ob_start's buffer:
使用以下代码段通过帮助 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");
?>
回答by dogmatic69
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% 的页面大小。里程可能会有所不同
回答by Andrew
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 projectrather than creating your own regex from scratch.
preg_replace()
上述所有解决方案都存在单行注释、条件注释和其他陷阱的问题。我建议利用经过充分测试的Minify 项目,而不是从头开始创建自己的正则表达式。
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');
回答by Radek Pech
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 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' => '=', // and 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
回答by Mohamad Hamouday
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",
" ",
"",
" ",
"><",
">",
"=");
$Html = preg_replace($Search,$Replace,$Html);
return $Html;
}
回答by Avi Tyagi
Create a PHP file outside your document root. If your document root is
/var/www/html/
create the a file named minify.php one level above it
/var/www/minify.php
Copy paste the following PHP code into it
<?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.
auto_prepend_file = /var/www/minify.php
在文档根目录之外创建一个 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
Reference: http://websistent.com/how-to-use-php-to-minify-html-output/
参考:http: //websistent.com/how-to-use-php-to-minify-html-output/
回答by Teodor Sandu
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/?name=master#git%2Fmin%2Flib%2FMinify,你会发现 html/css/js minification在那里上课。
you can also try this: http://code.google.com/p/htmlcompressor/
你也可以试试这个:http: //code.google.com/p/htmlcompressor/
Good luck :)
祝你好运 :)
回答by ArjanSchouten
First of all gzip can help you more than a Html Minifier
首先,gzip 可以帮助您的不仅仅是 Html Minifier
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;
- With apache you can use mod_gzip
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;
- 使用 apache,您可以使用 mod_gzip
Second: with gzip + Html Minification you can reduce the file size drastically!!!
第二:使用gzip + Html Minification,您可以大大减少文件大小!!!
I've created this HtmlMinifier for PHP.
我已经为 PHP创建了这个HtmlMinifier。
You can retrieve it through composer: composer require arjanschouten/htmlminifier dev-master
.
您可以通过 composer: 检索它composer require arjanschouten/htmlminifier dev-master
。
There is a Laravel service provider. If you're not using Laravel you can use it from PHP.
有一个 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();
As you can see you can extend a lot of things in here and you can pass various options. Check the readmeto see all the available options.
正如你所看到的,你可以在这里扩展很多东西,你可以传递各种选项。检查自述文件以查看所有可用选项。
This HtmlMinifieris complete and safe. It takes 3 steps for the minification process:
这个HtmlMinifier是完整和安全的。缩小过程需要 3 个步骤:
- Replace critical content temporary with a placeholder.
- Run the minification strategies.
- Restore the original content.
- 用占位符临时替换关键内容。
- 运行缩小策略。
- 还原原始内容。
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
方法。
回答by Rudi Visser
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');
回答by Taufik Nurrohman
I have a GitHubgist contains PHP functions to minify HTML, CSS and JS files → https://gist.github.com/taufik-nurrohman/d7b310dea3b33e4732c0
我有一个GitHub要点,其中包含用于缩小 HTML、CSS 和 JS 文件的 PHP 函数 → https://gist.github.com/taufik-nurrohman/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(); ?>