PHP 페이지 HTML 출력을 축소하는 방법? 할 수있는 PHP 스크립트

Google 페이지 속도처럼 PHP 페이지 HTML 출력을 최소화 할 수있는 PHP 스크립트 또는 클래스를 찾고 있습니다.

어떻게해야합니까?



답변

CSS와 자바 스크립트

Javascript / CSS 파일을 축소하려면 다음 링크를 고려하십시오. https://github.com/mrclay/minify

HTML

GZip을 사용하여 HTML을 제공하도록 Apache에 지시하십시오. 이는 일반적으로 응답 크기를 약 70 % 줄입니다. (Apache를 사용하는 경우 gzip을 구성하는 모듈은 버전에 따라 다릅니다. Apache 1.3은 mod_gzip을 사용하고 Apache 2.x는 mod_deflate를 사용합니다.)

수락 인코딩 : gzip, 수축

콘텐츠 인코딩 : 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");

?>

답변

제대로하려면 gzip을 켜십시오. 다음과 같이 할 수도 있습니다.

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

이렇게하면 HTML을 한 줄, 탭 없음, 줄 바꿈 없음, 주석 없음으로 바꾸어 페이지 크기의 약 30 %를 제거 할 수 있습니다. 마일리지는 다를 수 있습니다


답변

위의 모든 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');

답변

나는 여러 가지 축소기를 시도했지만 너무 작거나 많이 제거했습니다.

이 코드는 여분의 빈 공간과 선택적 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

답변

이것은 나를 위해 일합니다.

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

답변

문서 루트 외부에 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/


답변

https://code.google.com/p/minify/source/browse/?name=master#git%2Fmin%2Flib%2FMinify 클래스를 확인할 수 있습니다.
html / css / js 축소가 나타납니다. 거기 수업.

당신이 시도 할 수 있습니다 : http://code.google.com/p/htmlcompressor/

행운을 빕니다 🙂