Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/277.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何缩小php页面html输出?_Php_Html_Minify - Fatal编程技术网

如何缩小php页面html输出?

如何缩小php页面html输出?,php,html,minify,Php,Html,Minify,我正在寻找一个php脚本或类,可以缩小我的php页面html输出像谷歌网页速度 我怎样才能做到这一点呢?如果你想正确地做到这一点,请打开gzip。您也可以这样做: $this->output = preg_replace( array( '/ {2,}/', '/<!--.*?-->|\t|(?:\r?\n[ \t]*)+/s' ), array( ' ', '' ), $t

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


我怎样才能做到这一点呢?

如果你想正确地做到这一点,请打开gzip。您也可以这样做:

$this->output = preg_replace(
    array(
        '/ {2,}/',
        '/<!--.*?-->|\t|(?:\r?\n[ \t]*)+/s'
    ),
    array(
        ' ',
        ''
    ),
    $this->output
);
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;
    }
}
$this->output=preg\u replace(
排列(
'/ {2,}/',
“/|\t |(?:\r?\n[\t]*)+/s”
),
排列(
' ',
''
),
$this->output
);

通过将html转换为一行、无选项卡、无新行、无注释,可以删除大约30%的页面大小。里程数可能会有所不同

您可以查看以下信息:

它可以作为PHP模块安装,并(正确、安全地)去除空白和所有其他污点,同时仍然输出完全有效的HTML/XHTML标记。它还将清理您的代码,这可能是一件好事,也可能是一件糟糕的事,这取决于您首先在编写有效代码方面有多出色;-)

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

ob_start('ob_gzhandler');

您可以签出这组类: ,您将在那里找到html/css/js缩小类

您也可以尝试以下方法:

祝你好运:)

CSS和Javascript 考虑以下链接以缩小Javascript/CSS文件:

HTML 告诉Apache使用GZip交付HTML—这通常会将响应大小减少70%左右。(如果您使用Apache,配置gzip的模块取决于您的版本:Apache 1.3使用mod_gzip,而Apache 2.x使用mod_deflate。)

接受编码: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");

?>

以上所有的
preg_replace()
解决方案都存在单行注释、条件注释和其他缺陷。我建议利用经过良好测试的正则表达式,而不是从头开始创建自己的正则表达式

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

我试过几款迷你手机,它们要么删除得太少,要么删除得太多

此代码删除多余的空格和可选的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);
  }
}
多亏了。 下面是a在cakePHP中使用它的方法:

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

    $this->output = preg_replace(
        array(
            '/ {2,}/',
            '/<!--.*?-->|\t|(?:\r?\n[ \t]*)+/s'
        ),
        array(
            ' ',
            ''
        ),
        $this->output
    );
    
    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;
        }
    }
    
    App::import('Vendor/min/lib/Minify/','HTML');
    App::import('Vendor/min/lib/Minify/','CommentPreserver');
    App::import('Vendor/min/lib/Minify/CSS/','Compressor');
    应用程序::导入('Vendor/min/lib/Minify/','CSS');
    App::import('Vendor/min/lib/','JSMin');
    类MinifyCodeHelper扩展了Helper{
    公共函数afterRenderFile($file,$data){
    if(Configure::read('debug')<1)//仅在生产模式下工作
    $data=Minify_HTML::Minify($data,array)(
    'cssMinifier'=>数组('Minify_CSS','Minify'),
    'jsMinifier'=>数组('JSMin','minify')
    ));
    返回$data;
    }
    }
    
  • 在AppController中启用我的助手

    public$helpers=array('Html','…','MinifyCode')

  • 5。。。瞧

    我的结论是:如果在您的服务器中禁用apache的deflate和headers模块,那么您的大小将减少21%,压缩请求将增加0.35s(这个数字就是我的例子)

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


    所以。。。我为什么这么做?”因为我的项目文档都在注释中(php、css和js),我的最终用户不需要看到这些;)

    首先,gzip比Html浏览器更能帮助您

  • :

  • Second:通过gzip+Html缩小,您可以大幅减小文件大小

    我创造了这个

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

    有一家拉威尔服务提供商。如果您没有使用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();
    
    //创建一个缩小上下文,该上下文将在缩小过程中使用
    $context=new MinifyContext(new placeholder container());
    //在上下文中保存html内容
    $context->setContents('myhtml…');
    $minify=新的minify();
    //启动流程并将其作为参数提供给上下文
    $context=$minify->run($context);
    //$context现在包含缩小的版本
    $minifiedContents=$context->getContents();
    
    正如您所看到的,您可以在这里扩展很多内容,并且可以传递各种选项。查看所有可用选项

    这是完整和安全的。缩小过程分为3个步骤:

  • 用占位符替换临时关键内容
  • 运行缩小策略
  • 恢复原始内容
  • 我建议您缓存视图的输出。缩小过程应为一次性过程。或者这样做,例如基于时间间隔

    当时没有创建明确的基准。不过,minifier可以根据您的标记将页面大小减少5-25%

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

    在文档根目录外创建一个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");?>
    

    参考资料:

    我有一个GitHub要点,其中包含用于缩小HTML、CSS和JS文件的PHP函数→

    下面介绍如何使用输出缓冲区动态缩小HTML输出:

    <?php
    
    include 'path/to/php-html-css-js-minifier.php';
    
    ob_start('minify_html');
    
    ?>
    
    <!-- HTML code goes here ... -->
    
    <?php echo ob_get_clean(); ?>
    

    您可以通过使用
    passthru
    exec
    调用一个经过良好测试的Java迷你程序,如
    <?php
    
    include 'path/to/php-html-css-js-minifier.php';
    
    ob_start('minify_html');
    
    ?>
    
    <!-- HTML code goes here ... -->
    
    <?php echo ob_get_clean(); ?>
    
    ob_start(function($b){
    if(strpos($b, "<html")!==false) {
    return str_replace(PHP_EOL,"",$b);
    } else {return $b;}
    });
    
    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;
    }