PhpRiot
Become Zend Certified

Prepare for the ZCE exam using our quizzes (web or iPad/iPhone). More info...


When you're ready get 7.5% off your exam voucher using voucher CJQNOV23 at the Zend Store

Accessor Methods

The main goal of the response object is to provide easy access to various response parameters.

  • getStatus(): Get the HTTP response status code (eg. 200, 504, etc.)

  • getMessage(): Get the HTTP response status message (eg. "Not Found", "Authorization Required")

  • getBody(): Get the fully decoded HTTP response body

  • getRawBody(): Get the raw, possibly encoded HTTP response body. if the body was decoded using GZIP encoding for example, it will not be decoded.

  • getHeaders(): Get the HTTP response headers as an associative array (eg. 'Content-type' => 'text/html')

  • getHeader($header): Get a specific HTTP response header, specified by $header

  • getHeadersAsString($status_line, $br): Get the entire set of headers as a string. If $status_line is TRUE (default), the first status line (eg. "HTTP/1.1 200 OK") will also be returned. Lines are broken with the $br parameter (Can be, for example, "<br />". Default "\n")

  • asString($br): Get the entire response message as a string. Lines are broken with the $br parameter (Can be, for example, "<br />". Default "\n"). You can also use the magic method __toString() when casting the object as a string. It will then proxy to asString().

Example 504. Using Zend_Http_Response Accessor Methods

<?php
if ($response->getStatus() == 200) {
  echo 
"The request returned the following information:<br />";
  echo 
$response->getBody();
} else {
  echo 
"An error occurred while fetching data:<br />";
  echo 
$response->getStatus() . ": " $response->getMessage();
}


Always check return value

Since a response can contain several instances of the same header, the getHeader() method and getHeaders() method may return either a single string, or an array of strings for each header. You should always check whether the returned value is a string or array.

Example 505. Accessing Response Headers

<?php
$ctype 
$response->getHeader('Content-type');
if (
is_array($ctype)) $ctype $ctype[0];

$body $response->getBody();
if (
$ctype == 'text/html' || $ctype == 'text/xml') {
  
$body htmlentities($body);
}

echo 
$body;


Zend Framework