CakePHP 3.4 introduces a stricter approach to header handling, prohibiting the direct echoing of data within controllers. Attempting to echo content, as seen below, results in the error "Unable to emit headers":
<code class="php">public function test() { $this->autoRender = false; echo json_encode(['method' => __METHOD__, 'class' => get_called_class()]); }</code>
Why CakePHP Complains
This practice is discouraged in CakePHP for several reasons:
Proper Output Methods
There are two recommended approaches for sending custom output:
Configure the Response Object:
Using the PSR-7 compliant interface:
<code class="php">$content = json_encode(['method' => __METHOD__, 'class' => get_called_class()]); $this->response = $this->response->withStringBody($content); $this->response = $this->response->withType('json'); return $this->response;</code>
Using the deprecated interface:
<code class="php">$content = json_encode(['method' => __METHOD__, 'class' => get_called_class()]); $this->response->body($content); $this->response->type('json'); return $this->response;</code>
Use a Serialized View:
<code class="php">$content = ['method' => __METHOD__, 'class' => get_called_class()]; $this->set('content', $content); $this->set('_serialize', 'content');</code>
This method requires the Request Handler component and appropriate URL mapping to utilize JSON rendering.
Reference Material
For more information, refer to the following resources:
The above is the detailed content of How to Output Custom HTTP Body with CakePHP 3.4?. For more information, please follow other related articles on the PHP Chinese website!