Modifying the response in Magento before its displayed on browser

Magento uses a response object to send all output. All output is added to this object, and then its sendResponse method is called.  If you need to modifying the response in Magento before its displayed on browser then you can listen to the event “http_response_send_before” and modify the output in the observer method.

Add the following lines in your custom module config.xml file to setup a listener for the “http_response_send_before

<global>
<events>
<http_response_send_before>
<observers>
<unique_label>
<type>singleton</type>
<class>group/observer</class>
<method>alterResponse</method>
</unique_label>
</observers>
</http_response_send_before>
</events>
</global>

Next we need to create an observer model. Create Model/Observer.php file to fetch the response output, modify it and set it back to the response object.

class Packagename_Modulename_Model_Observer
{
    public function alterResponse($observer) {
        $response = $observer->getResponse();
        $html     = $response->getBody();
        //modify response output here
        $response->setBody($html);
    }
}

To dig deeper the following classes may be referred

app/code/core/Mage/Core/Controller/Response/Http.php
lib/Zend/Controller/Response/Abstract.php

You can use the above event/observer approach to minify the HMTL output.

Comments

Leave a Comment

Back to top