Featured image of post Sending Strings as Files with CakePHP server response

Sending Strings as Files with CakePHP server response

With CakePHP it is quite easy to send any string as a subfile. As an example below is the creation of an ICS subfile (for a calendar invites)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
public function sendIcs()
{
  $icsString = $this->Calendars->generateIcs();
  $response = $this->response;

  // Inject string content into response body
  $response = $response->withStringBody($icsString);

  $response = $response->withType('ics');

  // Optionally force file download
  $response = $response->withDownload('filename_for_download.ics');

  // Return response object to prevent controller from trying to render
  // a view.
  return $response;
}

Example above is from official CakePHP book.