Comprimir salida HTML

27 views
Skip to first unread message

Sergio Gabriel Rodriguez

unread,
Jan 16, 2014, 12:01:05 PM1/16/14
to zend-framew...@googlegroups.com
Hola gente, reenvío un correo de la lista en inglés de ZF, un pequeño código para comprimir a salida html limpiando los espacios, lo probé y funciona perfecto.

Saludos.

Sergio Gabriel Rodriguez
Corrientes - Argentina

---------- Forwarded message ----------
From: mtymek <mty...@gmail.com>
Date: Thu, Jan 16, 2014 at 1:23 PM
Subject: [fw-general] Re: ZF2 - How to clear the contents of the html from blank lines?
To: fw-ge...@lists.zend.com


"finish" event should do it. Sometime ago I wrote a module that compresses
HTML by removing all extra whitespace, I'm attaching it here - maybe you
will find it useful.
It was working on a very simple website. For real-live app you may want to
for example check content-type header, to ensure it won't compress things
like JSON.


namespace HtmlCompressor

class Module
{
    /**
     * found somewhere on stack overflow
     */
    private function compress($html)
    {

preg_match_all('!(<(?:code|pre|script).*>[^<]+</(?:code|pre|script)>)!',$html,$pre);
        $html = preg_replace('!<(?:code|pre).*>[^<]+</(?:code|pre)>!',
'#pre#', $html);
        $html = preg_replace('#<!–[^\[].+–>#', '', $html);
        $html = preg_replace('/[\r\n\t]+/', ' ', $html);
        $html = preg_replace('/>[\s]+</', '><', $html);
        $html = preg_replace('/[\s]+/', ' ', $html);
        if (!empty($pre[0])) {
            foreach ($pre[0] as $tag) {
                $html = preg_replace('!#pre#!', $tag, $html,1);
            }
        }
        return $html;
    }

    public function compressHtml(MvcEvent $e)
    {
        $response = $e->getResponse();
        // compress HTML output
        $response->setContent($this->compress($response->getContent()));
    }

    public function onBootstrap(MvcEvent $e)
    {

        $app = $e->getApplication();
        $sm = $app->getServiceManager();
        $eventManager = $app->getEventManager();

        $eventManager->getSharedManager()->attach('Zend\Mvc\Application', 'finish',
array($this, 'compressHtml'), 1002);
    }

}




--
View this message in context: http://zend-framework-community.634137.n4.nabble.com/ZF2-How-to-clear-the-contents-of-the-html-from-blank-lines-tp4661474p4661476.html
Sent from the Zend Framework mailing list archive at Nabble.com.

--
List: fw-ge...@lists.zend.com
Info: http://framework.zend.com/archives
Unsubscribe: fw-general-...@lists.zend.com



Patricio Cardenas

unread,
Jan 16, 2014, 12:38:45 PM1/16/14
to zend-framew...@googlegroups.com
muchas gracias

lo voy a implementar



2014/1/16 Sergio Gabriel Rodriguez <sgrod...@gmail.com>

--
Has recibido este mensaje porque estás suscrito al grupo "Zend Framework-hispano" de Grupos de Google.
Para anular la suscripción a este grupo y dejar de recibir sus correos electrónicos, envía un correo electrónico a zend-framework-hi...@googlegroups.com.
Para publicar una entrada en este grupo, envía un correo electrónico a zend-framew...@googlegroups.com.
Visita este grupo en http://groups.google.com/group/zend-framework-hispano.
Para obtener más opciones, visita https://groups.google.com/groups/opt_out.



--
Atte.

Patricio Cardenas Garay
PHP Developer
Cel : 78329819

www.pcgaray.com


adrian gattorno gil

unread,
Jan 29, 2014, 11:38:16 AM1/29/14
to zend-framew...@googlegroups.com
muchas gracias lo había visto en stack overflow pero no ví que estubiera el código completo...

adrian gattorno gil

unread,
Feb 7, 2014, 10:59:56 AM2/7/14
to zend-framew...@googlegroups.com
Me he encontrado con algunos detalles en este metodo de compresion del html en cuanto a los script, le svoy a descibir lo que he hecho para solicionarlo para si alguno sabe una forma mejor la diga...
saludos...

en el método compress he tenido que hacer algunas modificaciones ya que códigos como este, que es muy utilizado para cargar jquery desde local cuando falle la carga desde el cdn de jquery o de google, no funcionan correctamente:
!window.jQuery && document.write('<script type=\"application/x-javascript\" src=\"/js/jquery/jquery-2.0.3.min.js\" charset=\"UTF-8\"></script>')

Concretamente la causa es que al eliminarse los saltos de lineas en ves de quedar de esta forma:
<script type="application/x-javascript">
    //<!--
    !window.jQuery && document.write('<script type="application/x-javascript" src="/js/jquery/jquery-2.0.3.min.js" charset="UTF-8"></script>')
    //-->
</script>

Queda así por lo que el código queda comentariado y no se ejecuta.
<script type="application/x-javascript">
//<!-- !window.jQuery && document.write('<script type="application/x-javascript" src="/js/jquery/jquery-2.0.3.min.js" charset="UTF-8"></script>') //-->
</script>

Lo que he hecho es que en el método compress en la linea

$html = preg_replace('/[\r\n\t]+/', ' ', $html);
he quitado \n que elimina los saltos de líneas, quedando:
$html = preg_replace('/[\r\t]+/', ' ', $html);

y he comentado la linea:

$html = preg_replace('/[\s]+/', ' ', $html);

finalmente me ha quedado así:


    private function compress($html)
    {

        preg_match_all('!(<(?:code|pre|script).*>[^<]+</(?:code|pre|script)>)!',$html,$pre);
                $html = preg_replace('!<(?:code|pre).*>[^<]+</(?:code|pre)>!','#pre#', $html);
                $html = preg_replace('#<!–[^\[].+–>#', '', $html);
                $html = preg_replace('/[\r\t]+/', ' ', $html);

                $html = preg_replace('/>[\s]+</', '><', $html);
//                $html = preg_replace('/[\s]+/', ' ', $html);

                if (!empty($pre[0])) {
                    foreach ($pre[0] as $tag) {
                        $html = preg_replace('!#pre#!', $tag, $html,1);
                    }
                }
                return $html;
    }
   

El jueves, 16 de enero de 2014 12:01:05 UTC-5, sergabrod escribió:
Reply all
Reply to author
Forward
0 new messages