James Butler James Butler - 5 months ago 9
PHP Question

How do I set/change content-type headers for an entire Zend Framework Application

I've already seen this question:
Zend Framework how to set headers
and I am aware of how to set headers on a per controller basis.


$this->getResponse()
->setHeader('Content-type', 'text/html; charset=utf-8')


However i'd like to set the content-header in my config file and have it set all my responses to use that content type. Is there some built in method/convention I'm missing out on? I'll settle for setting something in the bootstrap as 2nd best choice.

This is in my config:

resources.view.doctype = "XHTML1_STRICT"
resources.view.encoding = "UTF-8"
resources.view.contentType = "text/html;charset=utf-8"


and I'm using modules and layouts if its any help (default module in this case)

Regards.

Answer

You can write a plugin for this which automatically sets the content-type to a default when no other content-types have been set already. Example:

class YourApp_Controller_Plugin_ContentType extends Zend_Controller_Plugin_Abstract
{
    public function dispatchLoopShutdown()
    {
        $response = $this->getResponse();
        $http_headers = $response->getHeaders();

        /**
         * Check whether the Content-Type header is defined.
         */
        $content_type_found = false;
        foreach ($http_headers as $_header)
        {
            if ($_header['name'] === 'Content-Type')
            {
                $content_type_found = true;
                break;
            }
        }

        /**
         * When no Content-Type has been set, set the default text/html; charset=utf-8
         */
        if (!$content_type_found)
        {
            $response->setHeader('Content-Type', 'text/html; charset=utf-8');
        }
    }
}