yii\web\Response::setDownloadHeaders PHP Method

setDownloadHeaders() public method

Sets a default set of HTTP headers for file downloading purpose.
public setDownloadHeaders ( string $attachmentName, string $mimeType = null, boolean $inline = false, integer $contentLength = null )
$attachmentName string the attachment file name
$mimeType string the MIME type for the response. If null, `Content-Type` header will NOT be set.
$inline boolean whether the browser should open the file within the browser window. Defaults to false, meaning a download dialog will pop up.
$contentLength integer the byte length of the file being downloaded. If null, `Content-Length` header will NOT be set.
    public function setDownloadHeaders($attachmentName, $mimeType = null, $inline = false, $contentLength = null)
    {
        $headers = $this->getHeaders();
        $disposition = $inline ? 'inline' : 'attachment';
        $headers->setDefault('Pragma', 'public')->setDefault('Accept-Ranges', 'bytes')->setDefault('Expires', '0')->setDefault('Cache-Control', 'must-revalidate, post-check=0, pre-check=0')->setDefault('Content-Disposition', $this->getDispositionHeaderValue($disposition, $attachmentName));
        if ($mimeType !== null) {
            $headers->setDefault('Content-Type', $mimeType);
        }
        if ($contentLength !== null) {
            $headers->setDefault('Content-Length', $contentLength);
        }
        return $this;
    }

Usage Example

 /**
  * Formats the specified response.
  * @param \yii\web\Response $response the response to be formatted.
  */
 public function format($response)
 {
     //$response->getHeaders()->set('Content-Type', 'text/csv; charset=UTF-8');
     $response->setDownloadHeaders(basename(\Yii::$app->request->pathInfo) . '.csv', 'text/csv');
     if ($response->data === null) {
         return;
     }
     $handle = fopen('php://memory', 'r+');
     /** @var array $data should be output of \yii\rest\Serializer configured in current controller */
     $data = $response->data;
     if (!isset($data['items'])) {
         // single model
         fputcsv($handle, array_keys($data));
         fputcsv($handle, array_map(function ($value) {
             return is_array($value) ? print_r($value, true) : (string) $value;
         }, array_values($data)));
     } else {
         // a collection of models
         if (($firstRow = reset($data['items'])) !== false) {
             fputcsv($handle, array_keys($firstRow));
         }
         foreach ($data['items'] as $item) {
             fputcsv($handle, $item);
         }
     }
     rewind($handle);
     // mb_convert_encoding($csv, 'iso-8859-2', 'utf-8')
     $response->content = stream_get_contents($handle);
     fclose($handle);
 }
All Usage Examples Of yii\web\Response::setDownloadHeaders