1

A lot of Magento tutorials are using echo to output controller text. However, using echo can cause weird problems, like the infamous “Headers already sent” error.

I understand that the right way to return response is by using setBody(), eg $this->getResponse()->setBody($text);, but for some cases I prefer using echo for convenience (returning by parts vs returning all at once).

So my question is - is there a "safe" Magento way to use echo in controllers? or is it a big no-no and should never be used?

PS I can use collect data myself and just call setBody() at the end (eg do something like "$ret .= ..." instead of echo), but in this case an uncaught error will not give me any output, while using echo will at least show me some of the output, up until the error. I'm talking about debug pages here so partial is still very useful :)

Manashvi Birla
  • 8,833
  • 9
  • 27
  • 53
Ronen Ness
  • 587
  • 6
  • 19

2 Answers2

2

There is one major difference between the use of echo and a Mage_Core_Controller_Response_Http object.

Let's have a look at how the response is sent via the parent abstract class Zend_Controller_Response_Abstract :

public function sendResponse()
{
    $this->sendHeaders();

    if ($this->isException() && $this->renderExceptions()) {
        $exceptions = '';
        foreach ($this->getException() as $e) {
            $exceptions .= $e->__toString() . "\n";
        }
        echo $exceptions;
        return;
    }

    $this->outputBody();
}

As you might guess, the outputBody method is just an echo:

public function outputBody()
{
    $body = implode('', $this->_body);
    echo $body;
}

However, the interesting part is the sendHeaders method, I suggest you check both method from Mage_Core_Controller_Response_Http and Zend_Controller_Response_Abstract

With this method, no HTTP header is being sent, I suggest you have a read here if you're not familiar with HTTP headers: http://www.faqs.org/rfcs/rfc2616.html

Using echo only can result in various problems, the most known with Magento is the Headers already sent error message.

Raphael at Digital Pianism
  • 70,385
  • 34
  • 188
  • 352
  • 1
    adding to your asnwer: I looked at the code of Zend_Controller_Response_Abstract and found the 'appendBody()' function, which gives the convenience of sending output in lines and not all in once. so I replaced all my echos with it and it looks good now (no already sent reports etc). – Ronen Ness Apr 14 '16 at 09:10
0

It can be helpful to use echo when debugging something. In any other case use Magento response API. Exception to that would be if you want to output something to browser directly, like file download or raw image for example. Of course in that case you will need to handle headers manually. If you are using the controller in regular Magento request, then do not echo except for some quick debugging.

Petar Dzhambazov
  • 1,423
  • 13
  • 17